Compare commits

...

2 Commits

Author SHA1 Message Date
69ca7c217e feat merge video and audio. 2024-09-30 10:57:02 +08:00
74b205a32c feat 拼接音频文件路径. 2024-09-30 10:19:18 +08:00

View File

@ -1,6 +1,7 @@
use std::fs;
use std::io::Result; use std::io::Result;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command;
use std::{fs, io};
fn guess_video_path(path: &Path) -> Result<PathBuf> { fn guess_video_path(path: &Path) -> Result<PathBuf> {
let mut largest_size = 0; let mut largest_size = 0;
@ -12,7 +13,7 @@ fn guess_video_path(path: &Path) -> Result<PathBuf> {
} }
let size = entry_path.metadata()?.len(); let size = entry_path.metadata()?.len();
if size > largest_size { if size >= largest_size {
largest_size = size; largest_size = size;
largest_file = entry_path.into(); largest_file = entry_path.into();
} }
@ -21,10 +22,65 @@ fn guess_video_path(path: &Path) -> Result<PathBuf> {
Ok(largest_file) Ok(largest_file)
} }
pub fn merge_video_from_path(path: &Path) -> Result<()> { fn convert_audio_to_aac(path: &Path) -> Result<()> {
let video_path = guess_video_path(path)?; let save_path = path.with_extension("aac");
let video_name = video_path.file_name().unwrap(); let output = Command::new("ffmpeg")
println!("Merging video {:?}", video_name); .arg("-y")
.arg("-hide_banner")
.arg("-i").arg(path)
.arg("-c").arg("copy")
.arg(save_path)
.spawn()?.wait_with_output();
match output {
Ok(res) => {
if !res.status.success() {
return Err(io::Error::new(io::ErrorKind::Other, format!("ffmpeg exited with status {}", res.status)));
}
}
Err(e) => return Err(e)
}
Ok(()) Ok(())
} }
fn merge(video_path: &Path, audio_path: &Path) -> Result<()> {
let origin_video_extension = video_path.extension().unwrap().to_str().unwrap();
let origin_filename = format!("original.{}", &origin_video_extension);
let origin_path = video_path.parent().unwrap().join(origin_filename);
fs::rename(video_path, &origin_path)?;
let output = Command::new("ffmpeg")
.arg("-y")
.arg("-hide_banner")
.arg("-i").arg(origin_path)
.arg("-i").arg(audio_path)
.arg("-c").arg("copy")
.arg(video_path)
.spawn()?.wait_with_output();
match output {
Ok(res) => {
if !res.status.success() {
return Err(io::Error::new(io::ErrorKind::Other, format!("ffmpeg exited with status {}", res.status)));
}
}
Err(e) => return Err(e)
}
Ok(())
}
pub fn merge_video_from_path(path: &Path) -> Result<()> {
let video_path = guess_video_path(path)?;
let video_name = video_path.file_name().unwrap().to_str().unwrap();
let video_extension = video_path.extension().unwrap();
let audio_name = format!("{}.m4a", &video_name[..video_name.len() - video_extension.len() - 1]);
let audio_path = video_path.parent().unwrap().join(audio_name);
if !audio_path.exists() {
return Err(io::Error::new(io::ErrorKind::NotFound, "Audio file does not exist"));
}
convert_audio_to_aac(&audio_path).expect("Audio file corrupted.");
merge(&video_path, &audio_path)
}