我需要将 wav 文件从格式1转换为格式 2
格式 1 :μ律,8000Hz,64 kbps,单声道
格式2:集装箱波浪 编码 PCM 速率 16K 示例格式 16 位 通道单声道
以下是代码片段:
File file = new File("audio_before_conversion.wav");
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true , true);
AudioInputStream audioInputStream1 = new AudioInputStream(
new FileInputStream(file), audioFormat, numFrames);
AudioSystem.write(audioInputStream1, Type.WAVE,
new File("audio_after_conversion.wav"));
问题:但是,这不起作用。它播放了一些噪音,也减少了我的音频文件长度。
编辑1:木法到μ法
以下代码对我有用——
File sourceFile = new File("<Source_Path>.wav");
File targetFile = new File("<Destination_Path>.wav");
AudioInputStream sourceAudioInputStream = AudioSystem.getAudioInputStream(sourceFile);
AudioInputStream targetAudioInputStream=AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, sourceAudioInputStream);
System.out.println("Sample Rate1 "+targetAudioInputStream.getFormat().getFrameRate());
AudioFormat targetFormat = new AudioFormat(new AudioFormat.Encoding("PCM_SIGNED"), 16000, 16, 1, 2, 8000, false);
AudioInputStream targetAudioInputStream1 = AudioSystem.getAudioInputStream(targetFormat, targetAudioInputStream);
System.out.println("Sample Rate "+targetAudioInputStream1.getFormat().getFrameRate());
try {
AudioSystem.write(targetAudioInputStream1, AudioFileFormat.Type.WAVE, targetFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
您需要使用AudioSystem
并将格式转换和音频写入分为两个不同的步骤:
final File file = new File("audio_before_conversion.wav");
// open the audio stream
final AudioInputStream pcmStream8k = AudioSystem.getAudioInputStream(file);
// specify target format
final AudioFormat targetFormat = new AudioFormat(16000, 16, 1, true , true);
// this converts your audio stream
final AudioInputStream pcmStream16k = AudioSystem.getAudioInputStream(targetFormat, pcmStream8k);
// this writes the audio stream
AudioSystem.write(pcmStream16k, AudioFileFormat.Type.WAVE, new File("audio_after_conversion.wav"));