Adding delay while Mediaplayer loops

谁说我不能喝 提交于 2019-12-13 04:36:33

问题


Playing .wav file using MediaPlayer class. As I need to loop the Audio I've set .setLooping(true); . So obviously, the doubt is how do I add a delay each time the audio plays, say I want a delay of 5000 .

The answers to similar questions here doesn't work in my case. Any help would be appreciated. Here is my code:

 Button Sample = (Button)findViewById(R.id.samplex);
    Sample.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

    String filePath = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";

            try {
                mp.setDataSource(filePath);
                mp.prepare();
                mp.setLooping(true);

            }
            catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mp.start();

        }


    });

回答1:


You need to register 2 listeners (on completion and on error) and then you would need to delay next play in on completion callback. Reason for the error listener is to return true to avoid calling on completion event whenever there is an error - explanation here

private final Runnable loopingRunnable = new Runnable() {
    @Override
    public void run() {
        if (mp != null) {
            if (mp.isPlaying() {
                mp.stop();
            }
            mp.start();
        }
    }
}

mp.setDataSource(filePath);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        button.postDelayed(loopingRunnable, 5000);
    }
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    ...
    return true;
});

mp.prepare();
// no need to loop it since on completion event takes care of this
// mp.setLooping(true);

Whenever your destruction method is (Activity.onDestroyed(), Fragment.onDestroy(), View.onDetachedFromWindow()), ensure you are removing the runnable callbacks, e.g.

@Override
protected void onDestroy() {
    super.onDestroy();
    ...
    button.removeCallbacks(loopingRunnable);

    if (mp != null) {
        if (mp.isPlaying()) {
            mp.stop();
        }

        mp.release();
        mp = null;
    }
}


来源:https://stackoverflow.com/questions/31247607/adding-delay-while-mediaplayer-loops

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