我的用例是我有一个应用程序,用户可以在其中按下一个按钮,它可以在外部扬声器和有线耳机/蓝牙设备之间切换。如果用户连接到有线耳机或蓝牙耳机设备,我想将有线耳机或蓝牙的音频输出切换到外部扬声器,然后当他们再次单击时,重新启用有线耳机/蓝牙音频输出.
有谁知道这可以在 Android 10 中完成?我在这篇文章中尝试了以下示例,但它并不总是适用于蓝牙情况。我的代码如下:
if (shouldEnableExternalSpeaker) {
audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
audioManager.isSpeakerphoneOn = true
if (isBlueToothConnected) {
audioManager.stopBluetoothScoOn()
}
} else {
if (isBlueToothConnected) {
audioManager.startBluetoothSco()
}
audioManager.mode = AudioManager.NORMAL
audioManager.isSpeakerphoneOn = false
}
Run Code Online (Sandbox Code Playgroud)
我还拥有对用户音频的必要权限:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
我认为您应该将处理分为 3 种情况,通过以下方式播放声音:
生成的代码可能看起来像这样。
if(shouldEnableExternalSpeaker) {
if(isBlueToothConnected) {
// 1. case - bluetooth device
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.startBluetoothSco();
mAudioManager.setBluetoothScoOn(true);
} else {
// 2. case - wired device
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.stopBluetoothSco();
mAudioManager.setBluetoothScoOn(false);
mAudioManager.setSpeakerphoneOn(false);
}
} else {
// 3. case - phone speaker
mAudioManager.setMode(AudioManager.MODE_NORMAL);
mAudioManager.stopBluetoothSco();
mAudioManager.setBluetoothScoOn(false);
mAudioManager.setSpeakerphoneOn(true);
}
Run Code Online (Sandbox Code Playgroud)
尽管我AudioManager最近没有使用过,但这在过去对我有用。
| 归档时间: |
|
| 查看次数: |
5017 次 |
| 最近记录: |