我最后使用的解决方案是首先编写代码来播放波形文件的一部分(即从xxx ms到xxx ms),因为我还需要支持这种文件格式。这是代码:
File soundFile = new File(this.audioFilePath);
AudioInputStream originalAudioInputStream = AudioSystem.getAudioInputStream(soundFile);
AudioFormat audioFormat = originalAudioInputStream.getFormat();
float startInBytes = (startTimeinMs / 1000 * audioFormat.getSampleRate() * audioFormat.getFrameSize());
float lengthInFrames = ((endTimeinMs - startTimeinMs) / 1000 * audioFormat.getSampleRate());
originalAudioInputStream.skip((long) startInBytes);
AudioInputStream partAudioInputStream = new AudioInputStream(originalAudioInputStream,
originalAudioInputStream.getFormat(), (long) lengthInFrames);
// code to actually play the audio input stream here
一旦它工作了,我编写了这段代码来将 MP3 转换为临时波形文件(然后我可以与上面的代码一起使用)——这是使用 JLayer 和 MP3SPI。我确实尝试直接在转换后的音频流上执行上述操作,而无需先写入文件,但无法使其正常工作。我只使用可以立即转换/写出的小型 MP3 文件,所以我对这个解决方案很满意。
File soundFile = new File(this.inputFilePath);
AudioInputStream mp3InputStream = AudioSystem.getAudioInputStream(soundFile);
AudioFormat baseFormat = mp3InputStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
AudioInputStream convertedAudioInputStream = AudioSystem.getAudioInputStream(decodedFormat, mp3InputStream);
File outputFile = new File(this.outputFilePath);
AudioSystem.write(convertedAudioInputStream, AudioFileFormat.Type.WAVE, outputFile);