如果某些活动在Android中播放视频,如何暂停背景音乐?

时间:2017-06-19 16:10:26

标签: android

如果在其他活动中播放视频,有什么方法可以暂停背景音乐?

我已使用此代码在所有活动中播放音乐:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.ultahcover);
  mediaPlayer.start();

  memories.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        mediaPlayer.pause();
        length=mediaPlayer.getCurrentPosition();
        startActivity(new Intent(MainActivity.this, kenangan_kita.class));
      }
      // here's an activity with video player
    });

@Override
  protected void onPause() {
    super.onPause();
    mediaPlayer.isPlaying(); //this is work to play on all activity but clashes with video music
  }

任何想要避免冲突音乐播放器的想法?

请帮帮我

1 个答案:

答案 0 :(得分:0)

只是请求音频焦点,这会通知其他应用你现在需要关注的焦点,他们应该暂停播放:

AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                         // Use the music stream.
                         AudioManager.STREAM_MUSIC,
                         // Request permanent focus.
                         AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback
}

查看此官方指南:Handling Changes in Audio Output