1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

バックグラウンド音源をミュート

Posted at

効果音を再生する時に裏で音楽再生アプリ等で再生していると音が重なって聞き取れない!
という時にバックグラウンドの音を一時的にミュートする方法

バックグラウンド音源をミュート

AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	AudioFocusRequest focusRequest =
		new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
			.setAudioAttributes(new AudioAttributes.Builder()
			.setUsage(AudioAttributes.USAGE_MEDIA)
			.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
			.build())
		.setAcceptsDelayedFocusGain(true)
		.setOnAudioFocusChangeListener(audio_focus_listener)
		.build();
	audioManager.requestAudioFocus(focusRequest);
} else {
	audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
}

バックグラウンド音源のミュートを解除

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	AudioFocusRequest focusRequest =
		new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
			.setAudioAttributes(new AudioAttributes.Builder()
			.setUsage(AudioAttributes.USAGE_MEDIA)
			.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
			.build())
		.setAcceptsDelayedFocusGain(true)
		.setOnAudioFocusChangeListener(audio_focus_listener)
		.build();
	audioManager.abandonAudioFocusRequest(focusRequest);
} else{
	audioManager.abandonAudioFocus(null);
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?