耳机移除时暂停视频延迟

时间:2015-03-13 19:15:21

标签: android video headset

我正在播放视频并尝试在移除耳机时将其暂停。但不幸的是,音乐/视频停止后大约1-2秒的时间延迟。当我将它用于音乐播放器而不是视频播放器时,同一段代码可以正常工作。有人可以帮忙吗?

的活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
// Register headset receiver
    registerReceiver(headsetReceiver,
            new IntentFilter(Intent.ACTION_HEADSET_PLUG));}


// If headset gets unplugged, stop music and service.
private final BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
    private boolean headsetConnected = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        // Log.v("TAG", "ACTION_HEADSET_PLUG Intent received");
        if (intent.hasExtra("state")) {
            if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
                headsetConnected = false;
                headsetSwitch = 0;

            } else if (!headsetConnected
                    && intent.getIntExtra("state", 0) == 1) {
                headsetConnected = true;
                headsetSwitch = 1;

            }

        }

        switch (headsetSwitch) {
            case (0):
                headsetDisconnected();
                break;
            case (1):
                break;
            default:
                break;
        }
    }

};

private void headsetDisconnected() {
    if(videoInterface!=null)
        videoInterface.stopVideo();

}

片段:

public class VideoPlayerFragment extends Fragment implements VideoInterface
{
 @Override
 public void onAttach(Activity activity) {
    super.onAttach(activity);
    ((VideoPlayer)getActivity()).videoInterface = this;
}
 @Override
 public void stopVideo() {   // interface method
    if (mediaPlayer != null && mediaPlayer.isPlaying())
       mediaPlayer.pause();
}

2 个答案:

答案 0 :(得分:0)

您随时可以回放视频;

    int currTime = mediaplayer.getcurrentposition();
    int newTime = currTime - 3000; // 3k milliseconds
    mediaplayer.seekTo(newTime);

答案 1 :(得分:0)

使用以下代码解决它。参考:http://developer.android.com/training/managing-audio/audio-output.html

IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);

    registerReceiver(headsetReceiver, intentFilter);

// If headset gets unplugged, stop music and service.
private final BroadcastReceiver headsetReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
            // Pause the playback
            headsetDisconnected();
        }

        }

};

private void headsetDisconnected() {
    if(videoInterface!=null)
        videoInterface.stopVideo();

}