Android开发之Audio音频信号输出频道选择

来源:互联网 发布:linux daemon 命令 编辑:程序博客网 时间:2024/06/06 01:44

最近,公司大boss让我给app添加蓝牙耳机使用功能,功能说明是:手机连接蓝牙耳机状态下,可通过蓝牙耳机进行语音的录入和输出。

我上网查了一些资料,选择了较适合的一种方式进行蓝牙通道的打开与关闭:

public void startBluetooth() {
Log.d("SpeechApp", "startBluetooth enter");
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.setBluetoothScoOn(true);
mAudioManager.startBluetoothSco();

   //关闭手机外放功能
mAudioManager.setMicrophoneMute(false);
}

public void stopBluetooth() {
Log.d("SpeechApp", "stopBluetooth enter");
mAudioManager.setBluetoothScoOn(false);
mAudioManager.stopBluetoothSco();
}

但是测试发现,这种设置的前提下,当手机不连接蓝牙耳机时,是不能通过手机原外放播放器播放语音的,应该是mAudioManager.setMicrophoneMute(false);这句话关闭了。但是插入有线耳机的状态下,是可以通过手机录音,通过有线耳机播放声音的。所以,我认为,需要对这三种通道的音频输入输出进行仔细排查。实现较清晰的功能:当连接蓝牙耳机时,通过蓝牙耳机进行语音的输入输出(录音与播放);当连接有线耳机时,可通过手机录音,通过有线耳机播放;当无耳机(蓝牙和有线)连接时,使用手机的原录音器和播放器。代码实现为:

if (isBTConnected()) {
// 连接蓝牙,使用蓝牙耳机进行音频输入输出
startBluetooth();
} else if (mAudioManager.isWiredHeadsetOn()) {
//连接有线耳机,使用有线耳机通信
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.stopBluetoothSco();
mAudioManager.setBluetoothScoOn(false);
mAudioManager.setSpeakerphoneOn(false);
} else {
// 未连接耳机,使用手机外放音
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.stopBluetoothSco();
mAudioManager.setBluetoothScoOn(false);
mAudioManager.setSpeakerphoneOn(true);
}

// 判断有无蓝牙设备连接
public boolean isBTConnected() {
BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();
// adapter也有getState(), 可获取ON/OFF...其它状态
int a2dp = blueadapter.getProfileConnectionState(BluetoothProfile.A2DP); // 可操控蓝牙设备,如带播放暂停功能的蓝牙耳机
int headset = blueadapter.getProfileConnectionState(BluetoothProfile.HEADSET); // 蓝牙头戴式耳机,支持语音输入输出
int health = blueadapter.getProfileConnectionState(BluetoothProfile.HEALTH);
return blueadapter != null && (a2dp == BluetoothAdapter.STATE_CONNECTED
|| headset == BluetoothAdapter.STATE_CONNECTED || health == BluetoothAdapter.STATE_CONNECTED);
}

public void startBluetooth() {
Log.d("SpeechApp", "startBluetooth enter");
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.setBluetoothScoOn(true);
mAudioManager.startBluetoothSco();
mAudioManager.setMicrophoneMute(false);
}

public void stopBluetooth() {
Log.d("SpeechApp", "stopBluetooth enter");
mAudioManager.setBluetoothScoOn(false);
mAudioManager.stopBluetoothSco();
}

再次提供两个参考链接:

http://blog.csdn.net/a791404623/article/details/76577129

http://blog.csdn.net/ansondroider/article/details/53911162