Clip可以播放mp3,但OpenAL只能保持静音(Java)

时间:2018-08-12 12:21:11

标签: java audio mp3 openal audioinputstream

当我使用sound.sampled.Clip测试mp3文件时,它会按预期播放。但是,当我使用OpenAL测试它时,我没有声音,也没有异常。

(我正在使用JMF的mp3plugin.jar以及OpenAL库)

这是一个很难用简单的代码演示的问题,因为使用openal需要大量的库和一些设置代码,但是我已经尽力了:

public static void main(String[] args) throws Exception {
    init(); //initialises OpenAL's device, context and alCapabilities

    Thread.sleep(1000);

    System.out.println("Clip");

    AudioInputStream ais = AudioSystem.getAudioInputStream(new File("grumble.mp3"));
    ais = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, ais);        
    Clip clip = AudioSystem.getClip();
    clip.open(ais);
    clip.start(); //plays both wav and mp3

    Thread.sleep(2000);

    clip.close();
    ais.close();
    System.out.println("OpenAL");

    ais = AudioSystem.getAudioInputStream(new File("grumble.mp3"));
    ais = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, ais);
    AudioFormat format = ais.getFormat();
    byte[] byteArr = new byte[ais.available()];
    ais.read(byteArr);

    ByteBuffer buf = BufferUtils.createByteBuffer(byteArr.length);
    buf.put(byteArr);
    byteArr = null;
    ais.close();
    buf.flip();

    int buffer = alGenBuffers();
    alBufferData(buffer, getALFormat(format), buf, (int)format.getSampleRate() );
    int source = alGenSources();
    alSourcei(source, AL_BUFFER, buffer);

    alSourcePlay(source); //plays wav, but is silent when trying to play mp3

    Thread.sleep(2000);

    System.out.println("end");
    alDeleteSources(source);
    alcCloseDevice(device);
}

public static int getALFormat(AudioFormat format)
{
    int alFormat = -1;
    if (format.getChannels() == 1) {
        System.out.println("mono ");
        if (format.getSampleSizeInBits() == 8) {
            alFormat = AL_FORMAT_MONO8;
        } else if (format.getSampleSizeInBits() == 16) {
            alFormat = AL_FORMAT_MONO16;
        } else {
            System.out.println("sample size: "+format.getSampleSizeInBits());
        }
    } else if (format.getChannels() == 2) {
        System.out.println("stereo ");
        if (format.getSampleSizeInBits() == 8) {
            alFormat = AL_FORMAT_STEREO8;
        } else if (format.getSampleSizeInBits() == 16) {
            alFormat = AL_FORMAT_STEREO16;
        } else {
            System.out.println("sample size: "+format.getSampleSizeInBits());
        }
    }

    return alFormat;
}

这就是我在控制台中得到的所有内容

Clip
OpenAL
stereo 
end

万一您想知道为什么我需要使用OpenAL,OpenAL提供了平移和音高操纵,而Clip则更容易处理。我已经能够平移和倾斜我提供的任何wav文件,而Clip经常不会执行任何操作(并且在调整平移/增益时会有延迟,而OpenAL是即时的)。

0 个答案:

没有答案