Android SoundPool: get notified when end of played

好久不见. 提交于 2019-11-27 21:18:52

It can't be done with SoundPool as far as I can tell.

The only audio 'player' that I know which can provide a completion notification is MediaPlayer - it's more of a complex beast than SoundPool but allows setting an OnCompletionListener to be notified when playback is complete.

This is what I do:

On startup I get the length of each sound-click using a MediaPlayer:

private long getSoundDuration(int rawId){
   MediaPlayer player = MediaPlayer.create(context, rawId);
   int duration = player.getDuration();
   return duration;
}

and store the sound plus the duration together (in a DTO-type object).

I have more than 100 short sound clips and SoundPool is my best option. I want to play one clip just after another clip is finished playing. Upon finding that there is no onCompletionListener() equivalent I chose to implement a runnable. This works for me because the first sound is between 1 and 2 seconds long so I have the duration of the runnable set at 2000. Hope they work on this class because its got lots of potential!

MediaPlayer is heavy and slow compared with SoundPool, but SoundPool doesn't have setOnCompletionListener. To cope with this issue I implemented a custom class from SoundPool with setOnCompletionListener.

usage: similar to MediaPlayer

creation:

SoundPoolPlayer mPlayer = SoundPoolPlayer.create(context, resId);
mPlayer.setOnCompletionListener(
    new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {  //mp will be null here
            Log.d("debug", "completed");
        }
    };
);
mPlayer.play();

pause:

mPlayer.pause();

stop:

mPlayer.stop();

resume:

mPlayer.resume();

isPlaying:

mPlayer.isPlaying();

any pull request is welcomed. I only implemented what I need here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!