Created
August 14, 2022 16:19
-
-
Save gitcrtn/327ebbea6c332e2f3fa589cf67a97d5e to your computer and use it in GitHub Desktop.
A batch converter from wav to mp3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "batch-wav2mp3" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
walkdir = "2.3.2" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::path::PathBuf; | |
use std::process::Command; | |
use walkdir::{DirEntry, WalkDir}; | |
fn is_wav(entry: &DirEntry) -> bool { | |
if entry.file_type().is_dir() { | |
return false; | |
} | |
let name = entry.file_name().to_str().unwrap(); | |
name.ends_with(".wav") && !name.starts_with(".") | |
} | |
fn convert_to_mp3(input: &String, output: &String) { | |
// ffmpeg -i input.wav -c:a libmp3lame -vn -b:a 128k output.mp3 | |
let mut ffmpeg = Command::new("ffmpeg") | |
.args(&["-i", input, "-c:a", "libmp3lame", "-vn", "-b:a", "128k", output]) | |
.spawn() | |
.unwrap(); | |
ffmpeg.wait().unwrap(); | |
} | |
fn check_ffmpeg() -> bool { | |
let status = Command::new("which") | |
.args(["ffmpeg"]) | |
.status() | |
.unwrap(); | |
status.success() | |
} | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
if args.len() != 2 { | |
println!("Error: A directory path must be set as argument."); | |
return; | |
} | |
let dir_path = PathBuf::from(args[1].clone()); | |
if !dir_path.is_dir() { | |
println!("Error: Specified path is not directory."); | |
return; | |
} | |
if !check_ffmpeg() { | |
println!("Error: ffmpeg not found."); | |
return; | |
} | |
let wav_files = WalkDir::new(dir_path.to_str().unwrap()) | |
.into_iter() | |
.filter_map(|e| { | |
if !is_wav(&e.as_ref().unwrap()) { | |
None | |
} else { | |
e.ok() | |
} | |
}) | |
.map(|e| e.path().to_str().unwrap().to_string()) | |
.collect::<Vec<String>>(); | |
println!("wav file count: {}", wav_files.len()); | |
for wav in wav_files.iter() { | |
let output = wav.replace(".wav", ".mp3"); | |
convert_to_mp3(wav, &output); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment