Python 代码调用启动ffmpeg命令实现格式转换器
我们将整个格式转换的功能划分为了四个模块,分别负责命令构建、命令执行、异常处理和参数验证。这种模块化的设计使得代码更加清晰和易于维护。
命令构建模块
构建ffmpeg命令的模块,负责根据输入输出参数构建正确的ffmpeg命令
class FFmpegCommandBuilder:
def __init__(self, input_file, output_file):
self.input_file = input_file
self.output_file = output_file
def build_command(self):
# 构建ffmpeg命令
command = [
'ffmpeg',
'-i', self.input_file,
'-c:v', 'libx264', # 选择视频编码器
'-c:a', 'aac', # 选择音频编码器
'-strict', 'experimental', # 设置音频编码器为experimental模式
self.output_file
]
return command
命令执行模块
执行ffmpeg命令的模块,负责启动子进程执行ffmpeg命令
import subprocess
class FFmpegCommandExecutor:
def execute_command(self, command):
# 执行ffmpeg命令
try:
subprocess.run(command, check=True)
print("Conversion completed successfully!")
except subprocess.CalledProcessError as e:
print("Conversion failed:", e)
异常处理模块
处理命令执行过程中的异常情况,如命令执行失败等
class FFmpegExceptionHandler:
def handle_exception(self, exception):
print("An error occurred during conversion:", exception)
参数验证模块
验证输入输出参数的模块,确保参数的合法性和完整性
class FFmpegParameterValidator:
def validate_parameters(self, input_file, output_file):
if not input_file or not output_file:
raise ValueError("Input and output files must be provided")
C++ 代码调用启动ffmpeg命令实现格式转换器
#include <iostream>
#include <string>
#include <stdexcept>
class FFmpegConverter {
public:
void convert(const std::string& input_file, const std::string& output_file);
private:
std::string buildCommand(const std::string& input_file, const std::string& output_file);
void executeCommand(const std::string& command);
};
void FFmpegConverter::convert(const std::string& input_file, const std::string& output_file) {
try {
std::string command = buildCommand(input_file, output_file);
executeCommand(command);
std::cout << "Conversion completed successfully!" << std::endl;
} catch (const std::exception& e) {
std::cerr << "Conversion failed: " << e.what() << std::endl;
throw; // 继续向上层抛出异常
}
}
std::string FFmpegConverter::buildCommand(const std::string& input_file, const std::string& output_file) {
// 构建ffmpeg命令
return "ffmpeg -i " + input_file + " -c:v libx264 -c:a aac -strict experimental " + output_file;
}
void FFmpegConverter::executeCommand(const std::string& command) {
// 执行ffmpeg命令
int result = std::system(command.c_str());
if (result != 0) {
throw std::runtime_error("FFmpeg command execution failed");
}
}
int main() {
FFmpegConverter converter;
std::string input_file = "input.avi";
std::string output_file = "output.mp4";
try {
converter.convert(input_file, output_file);
} catch (const std::exception& e) {
std::cerr << "An error occurred: " << e.what() << std::endl;
return 1;
}
return 0;
}
Java 代码调用启动ffmpeg命令实现格式转换器
在这个 Java 实现中,我们使用了 Process 类来执行命令,并通过 waitFor 方法等待命令执行完成。这样可以确保程序在命令执行完成后继续执行后续的代码逻辑。
import java.io.IOException;
public class FFmpegConverter {
public void convert(String inputFilePath, String outputFilePath) throws IOException, InterruptedException {
try {
String command = buildCommand(inputFilePath, outputFilePath);
executeCommand(command);
System.out.println("Conversion completed successfully!");
} catch (IOException | InterruptedException e) {
System.err.println("Conversion failed: " + e.getMessage());
throw e; // 继续向上层抛出异常
}
}
private String buildCommand(String inputFilePath, String outputFilePath) {
// 构建ffmpeg命令
return "ffmpeg -i " + inputFilePath + " -c:v libx264 -c:a aac -strict experimental " + outputFilePath;
}
private void executeCommand(String command) throws IOException, InterruptedException {
// 执行ffmpeg命令
Process process = Runtime.getRuntime().exec(command);
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new IOException("FFmpeg command execution failed with exit code " + exitCode);
}
}
public static void main(String[] args) {
FFmpegConverter converter = new FFmpegConverter();
String inputFilePath = "input.avi";
String outputFilePath = "output.mp4";
try {
converter.convert(inputFilePath, outputFilePath);
} catch (IOException | InterruptedException e) {
System.err.println("An error occurred: " + e.getMessage());
System.exit(1);
}
System.exit(0);
}
}