在Mediaplayer循环时添加延迟

时间:2015-07-06 13:50:13

标签: android android-mediaplayer

使用.wav课程播放MediaPlayer个文件。因为我需要循环音频我已设置.setLooping(true);。很明显,我怀疑的是每次音频播放时如何添加延迟,比如我想要延迟5000

这里类似问题的答案在我的案例中不起作用。任何帮助,将不胜感激。这是我的代码:

 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 个答案:

答案 0 :(得分:2)

您需要注册2个侦听器(完成时和出错时),然后您需要在完成回调时延迟下一个播放。错误监听器的原因是返回true以避免在出现错误时调用完成事件 - 解释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);

每当您的销毁方法为(Activity.onDestroyed(), Fragment.onDestroy(), View.onDetachedFromWindow())时,请确保删除可运行的回调,例如

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

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

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