Android AudioFocus with AudioTrack几乎不起作用



我使用AudioTrack像GPS导航一样播放音频。当然,我需要请求音频焦点,但我丑陋的代码并没有达到我的预期。我听到了audioTrack的声音,但我不能说音乐播放器(另一个应用程序)降低了它的音量。

AudioTrack:

audioTrack = new AudioTrack.Builder()
.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build())
.setAudioFormat(new AudioFormat.Builder()
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(SAMPLE_RATE)
.build())
.setTransferMode(AudioTrack.MODE_STREAM)
.setBufferSizeInBytes(intBufferSize)
.build();
audioTrack.play();

播放和聚焦请求:

maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
AudioAttributes playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
.setAudioAttributes(playbackAttributes)
//      .setAcceptsDelayedFocusGain(true)
//      .setOnAudioFocusChangeListener(afChangeListener)
.build();

int afresult = audioManager.requestAudioFocus(focusRequest);
Log.d(TAG, "Music request focus, result: " + afresult);
if (afresult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d(TAG, "Audio Focus is granted ");
audioTrack.setVolume(maxVolume*0.4f);
audioTrack.write(myAudioData, 0, myAudioData.length);
}
else if (afresult == AudioManager.AUDIOFOCUS_REQUEST_FAILED){
Log.d(TAG, "Audio Focus is failed ");
} else if (afresult == AudioManager.AUDIOFOCUS_REQUEST_DELAYED){
Log.d(TAG, "Audio Focus is delayed ");
}
audioManager.abandonAudioFocusRequest(focusRequest);

我还没有OnAudioFocusChangeListener,但我会实现它。那么为什么其他应用程序似乎不处理音频焦点丢失?AUDIOFOCUS_GAIN_TRANSIENT起作用,但AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK不起作用。我做错了什么?

提前谢谢你。

我意识到我的代码不能工作,因为我试图静音一个音乐流和播放另一个。我必须更改USAGECONTENT_TYPE属性。

可以是CONTENT_TYPE_SONIFICATION+USAGE_ASSISTANCE_SONIFICATIONCONTENT_TYPE_SPEECH+USAGE_VOICE_COMMUNICATION,如文档中所说。

希望能帮到别人。

相关内容

  • 没有找到相关文章

最新更新