在很多应用中,都存在使用蓝牙进行录音。
首先我们写一个BroadcastReceiver,进行监听蓝牙状态改变。
public class BluetoothStatusRec extends BroadcastReceiver{private String TAG = "BluetoothStatusRec";public static AudioManager mAudioManager ;private TurnOffBtn mTurnOffBtn;public static boolean mIsScoEnable = false;public BluetoothStatusRec(TurnOffBtn ins){mTurnOffBtn = ins;}@Overridepublic void onReceive(Context context, Intent intent) {mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);if(intent.getAction() == BluetoothDevice.ACTION_ACL_CONNECTED){Log.d(TAG,"连接成功");mTurnOffBtn.turnOn(); mTurnOffBtn.changeBtn();context.registerReceiver(new BroadcastReceiver() { //动态注册一个接受SCO状态改变的BroadcastReceiver@Overridepublic void onReceive(Context context, Intent intent) {int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);Log.d(TAG, "Audio SCO state: " + state);if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) { //SCO打开后(由手机输入变为蓝牙耳机输入),进行录音mAudioManager.setBluetoothScoOn(true);context.unregisterReceiver(this); //记得接收后解除注册//startRecord(); //进行录音,此时声源来自蓝牙耳机mTurnOffBtn.changeBtn();mTurnOffBtn.turnOn();Log.d("ww","连接sco成功");}else{try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}mAudioManager.startBluetoothSco();mTurnOffBtn.turnOff();mTurnOffBtn.changeBtnOn();}}}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));mAudioManager.startBluetoothSco();}if(intent.getAction() == BluetoothDevice.ACTION_ACL_DISCONNECTED){mTurnOffBtn.turnOff();mTurnOffBtn.changeBtnOn();}}public interface TurnOffBtn{void turnOff();void turnOn();void changeBtn();//连接蓝牙后禁用上面的start,stop按钮void changeBtnOn();//连接蓝牙后启用上面的start,stop按钮}}
然后在清单文件中声明这个BroadcastReceiver,
<receiver android:name="com.tanyaping.audio.blueRec.BluetoothStatusRec"><intent-filter><action android:name="BluetoothDevice.ACTION_ACL_CONNECTED" /><action android:name="BluetoothDevice.ACTION_ACL_DISCONNECTED" /></intent-filter></receiver>
这个蓝牙的广播(BluetoothStatusRec)也需要动态注册,
然后在清单文件中声明所需权限:
<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/><uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/><uses-permissionandroid:name="android.permission.MODIFY_AUDIO_SETTINGS" /><!-- 录音权限 --><uses-permission android:name="android.permission.RECORD_AUDIO" />
如果没有声明相应权限,耳机录音会失败。