how to know when soundpool finished playing audiofile?

喜夏-厌秋 提交于 2019-12-11 03:40:21

问题


I am using soundpool to play my recorded file. I just want to know that is there any way to know when soundpool finish playing. here is my working code below.

public void soundPool() {
    final float playbackSpeed = 1.5f;
    final SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC,
            100);

    final int soundId = soundPool.load(audiofile.getAbsolutePath(), 1);
    AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    final float volume = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
            soundPool.play(soundId, volume, volume, 1, 0, playbackSpeed);
        }
    });

}

回答1:


Yes you have to use mediaplayer for this..but using mediaplayer you can't do fast forwarding. my suggestion is you use sound pool for playing sound and before playing ,you can check time duration of sound using mediaplayer and when time wil finish you can manually stop soundpool. simple i have done this in a project.




回答2:


Unfortunately there is no listener provided for telling when SoundPool has finished playing a sample. If you need this functionality, use the MediaPlayer.

As a hack, you could get the length of your audio file from an audio editor in miliseconds (X), then set a timer in you app after you tell it to play. The timer is set to fire once after X milliseconds. This way you have an approximate idea whether your sound might have finished playing. However, this is a very unreliable approach and should be avoided if it can be helped. Instead, use the MediaPlayer class with MediaPlayer.OnCompletionListener().




回答3:


there is only one way that you take duration of that audio file and check it with thread.

soundPool.play(soundId, 1, 1, 1, 0, 1f);
new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
           // do your stuff song is finished

      }
},soundDuration);

Try It.



来源:https://stackoverflow.com/questions/18567242/how-to-know-when-soundpool-finished-playing-audiofile

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