使用Java播放奇异的WAV文件

时间:2018-10-17 10:47:27

标签: java javasound javax.sound.sampled

我有一个用ADPCM(id = 2),单声道,每个样本4位和一个“事实”块编码的WAV文件。很多东西都不会出现在“普通”波形中。

解析格式代码(此处2 == ADPCM)时,AudioInputStream的AudioFileReader类已经失败,它仅接受1,3,6和7。

还有另一种播放此类文件的方法吗?由于标准Java显然无法做到这一点。

这是文件:https://anonfile.com/c1ianfj5b5/music_wav

1 个答案:

答案 0 :(得分:0)

对于Windows(32/64)和macOS(64),可以使用FFSampledSP,v0.9.29或更高版本。您可以通过以下Maven依赖项来获取它:

<dependency>
    <groupId>com.tagtraum</groupId>
    <artifactId>ffsampledsp-complete</artifactId>
    <version>0.9.29</version>
</dependency>

或通过此下载link

一旦.jar在类路径中,以下代码应该起作用:

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class PlayADPCM {

    public static void main(final String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException {
        final File file = new File("your_adpcm_file.wav");
        final AudioInputStream stream = AudioSystem.getAudioInputStream(file);
        final AudioFormat format = stream.getFormat();
        System.out.println("Source format: " + format);
        final AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
            format.getSampleRate(), 16, format.getChannels(),
            format.getChannels()*2,
            format.getSampleRate(), format.isBigEndian());
        System.out.println("Target format: " + targetFormat);
        // convert source to target format
        final AudioInputStream playableStream = AudioSystem.getAudioInputStream(targetFormat, stream);
        // get a line and play it.
        final DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, targetFormat);
        final SourceDataLine line = (SourceDataLine)AudioSystem.getLine(lineInfo);
        line.open(targetFormat);
        line.start();
        final byte[] buf = new byte[1024*8];
        int justRead;
        while ((justRead = playableStream.read(buf))>0) {
            line.write(buf, 0, justRead);
        }
        playableStream.close();
        line.drain();
        line.close();
    }
}