java Process阻塞,需要关闭流

/**
* 把音频文件转换成mp3
*/
public static void ConvertM4aToMp3(String m4aFilePath, String outputFilePath) throws Exception {
Path path = Paths.get(m4aFilePath);
if(!Files.exists(path)){
throw new ServiceException(500, "转换MP3,临时文件不存在");
}
// 使用双引号包裹路径
//m4aFilePath = "\"" + m4aFilePath + "\"";
//outputFilePath = "\"" + outputFilePath + "\"";

// 明确分割命令参数
String[] cmd = {
"ffmpeg", // 或使用绝对路径
"-i", m4aFilePath,
"-c:a", "libmp3lame",
"-q:a", "0",
"-map_metadata", "0",
outputFilePath
};
log.info("输入文件路径:{},输出文件路径:{},执行命令:{}", m4aFilePath, outputFilePath, JSONUtil.toJsonStr(cmd));

try {
Process process = new ProcessBuilder(cmd).start();
process.getOutputStream().close();

// 读取输出和错误流(必须消费输出流,否则可能阻塞)
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

String line;
while ((line = reader.readLine()) != null) {
log.info("正确输出:" + line);
}
while ((line = errorReader.readLine()) != null) {
log.error("错误输出" + line); // FFmpeg 的错误输出通常在此处
}

int exitCode = process.waitFor();
log.info("FFmpeg 进程退出码: " + exitCode);
} catch (Exception e) {
log.info("转换mp3格式错误,源文件:{},错误信息:{}", m4aFilePath, ExceptionUtil.stacktraceToString(e));
}

}
posted on 2025-04-28 22:57  rana4504  阅读(18)  评论(0)    收藏  举报