From 69ca7c217ec203c7d67ba32e2c40ae3de3dfd354 Mon Sep 17 00:00:00 2001 From: licsber Date: Mon, 30 Sep 2024 10:57:02 +0800 Subject: [PATCH] feat merge video and audio. --- src/merge.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/src/merge.rs b/src/merge.rs index 472e74f..aaaeda0 100644 --- a/src/merge.rs +++ b/src/merge.rs @@ -1,5 +1,6 @@ use std::io::Result; use std::path::{Path, PathBuf}; +use std::process::Command; use std::{fs, io}; fn guess_video_path(path: &Path) -> Result { @@ -12,7 +13,7 @@ fn guess_video_path(path: &Path) -> Result { } let size = entry_path.metadata()?.len(); - if size > largest_size { + if size >= largest_size { largest_size = size; largest_file = entry_path.into(); } @@ -21,6 +22,54 @@ fn guess_video_path(path: &Path) -> Result { Ok(largest_file) } +fn convert_audio_to_aac(path: &Path) -> Result<()> { + let save_path = path.with_extension("aac"); + let output = Command::new("ffmpeg") + .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(()) +} + +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(); @@ -32,8 +81,6 @@ pub fn merge_video_from_path(path: &Path) -> Result<()> { return Err(io::Error::new(io::ErrorKind::NotFound, "Audio file does not exist")); } - println!("Merging video from {:?}", audio_path); - println!("Merging video {:?}", video_name); - - Ok(()) + convert_audio_to_aac(&audio_path).expect("Audio file corrupted."); + merge(&video_path, &audio_path) }