用于Android的异步音频播放器

时间:2017-03-19 16:35:08

标签: java android asynchronous audio audio-player

我创建了一个在Android中运行的Java应用程序。仅使用同步 MediaPlayer类准备并播放声音,延迟时间为50到80毫秒,这对于实时产品来说太大了。

因此,为了提高Java for Android中的声音播放器的性能(通过最小化其延迟),我正在寻找异步音频播放器或媒体播放器。

异步,因为这样可以避免在加载(准备)或播放声音时出现延迟

您是否知道可以在Java应用程序中导入的Android本机库或其他内容?

例如,我看过那个网址,但我不知道该怎么办?#34;插入"它在Java应用程序中?

https://developer.android.com/reference/android/media/AsyncPlayer.html

由于

1 个答案:

答案 0 :(得分:2)

我在书中写了一篇关于Android Audio的完整章节。这是我用来决定使用哪个API的流程图。您引用的旧AsyncPlayer已弃用,在我看来并不能真正解决您的延迟问题。 Media Player对于启动延迟来说更糟糕。根据您提供的信息,SoundPool可能是最佳选择。 AudioTrack为您提供最大的灵活性。

enter image description here

希望这会有所帮助。以下是使用soundPool API播放声音的代码摘录:

private void playSoundPool(int soundID) {
    int MAX_STREAMS = 20;
    int REPEAT = 0;
    SoundPool soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, REPEAT);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int soundId, int status) {
            int priority = 0;
            int repeat = 0;
            float rate = 1.f; // Frequency Rate can be from .5 to 2.0
            // Set volume
            AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
            float streamVolumeCurrent =
            mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
            float streamVolumeMax =
            mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            float volume = streamVolumeCurrent / streamVolumeMax;
            // Play it
            soundPool.play(soundId, volume, volume, priority, repeat, rate);
        }
    });
    soundPool.load(this, soundID, 1);
}