tips:.MP3文件转.WAV文件
一、格式转换示例1
1.引入库
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
2.工具类
public static File AacToWavFile(MultipartFile multipartFile) throws IOException, EncoderException {
String fileName = multipartFile.getOriginalFilename();
if (StringUtil.isEmpty(fileName)) {
throw new RuntimeException("文件名为空,上传失败");
}
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
File source = ConvertFile.convert(multipartFile);
File targetFile = new File(fileName.replace(suffix, "wav"));
// 音频编码属性
AudioAttributes audio = new AudioAttributes();
audio.setCodec("pcm_s16le"); // WAV格式的PCM编码
audio.setChannels(2); // 双声道
audio.setSamplingRate(44100); // 采样率44.1kHz
// 编码属性
EncodingAttributes encoding = new EncodingAttributes();
encoding.setOutputFormat("wav");
encoding.setAudioAttributes(audio);
// 执行转换
Encoder encoder = new Encoder();
encoder.encode(new MultimediaObject(source), targetFile, encoding);
return targetFile;
}
MultipartFile 转 File :
public static File convert(MultipartFile multipartFile) throws IOException {
File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
try (FileOutputStream fos = new FileOutputStream(file);
InputStream is = multipartFile.getInputStream()) {
int len;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
log.error("转换失败,error:{}",e.getMessage());
}
return file;
}
二、格式转换示例2
该处获取文件名及后缀:
public static File AacToWavConverter(MultipartFile multipartFile) throws IOException, InterruptedException {
try{
String fileName = multipartFile.getOriginalFilename();
if (StringUtil.isEmpty(fileName)) {
throw new RuntimeException("文件名为空,上传失败");
}
Map<String, Object> fileName1 = ConvertFile.getFileName(fileName);
String outputPath = fileName1.get("fileName").toString() + ".wav";
ProcessBuilder processBuilder = new ProcessBuilder(
"ffmpeg", "-i", fileName, "-acodec", "pcm_s16le", "-ar", "44100", outputPath
);
Process process = processBuilder.start();
// 读取错误流(避免进程阻塞)
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = errorReader.readLine()) != null) {
System.err.println(line);
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("FFmpeg执行失败,退出码:" + exitCode);
}
return new File(outputPath);
}catch (Exception e){
log.error("注册入声纹数据语音文件声纹识别错误!请重新上传分析");
return null;
}
}