1

我需要在我的 java 代码中播放 MP3 文件的一部分。我希望通过一个以毫秒为单位接受开始和停止时间的函数来做到这一点。

JLayer 包含一个名为 AdvancedPlayer 的类,它有一个接受帧中开始和停止位置的方法:

/**
 * Plays a range of MPEG audio frames
 * @param start The first frame to play
 * @param end       The last frame to play 
 * @return true if the last frame was played, or false if there are more frames.
 */
public boolean play(final int start, final int end) throws JavaLayerException
{
    boolean ret = true;
    int offset = start;
    while (offset-- > 0 && ret) ret = skipFrame();
    return play(end - start);
}

据此一帧持续 26 毫秒。但是我需要比这更精细的控制,即我可能希望从 40 毫秒到 50 毫秒。

我怎样才能做到这一点?我需要先将 MP3 转换为 .wav 吗?

4

2 回答 2

2

我最后使用的解决方案是首先编写代码来播放波形文件的一部分(即从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);
于 2009-07-02T06:58:28.433 回答
0

如果 26 毫秒是您在 MP3 文件中可以达到的最佳分辨率,那么您就不走运了。将其转换为 WAV 可能有效,但源数据(即 MP3)仍然具有基本分辨率限制。

出于好奇,为什么要播放 10 毫秒的音频?

于 2009-06-30T19:27:18.573 回答