如何使用蓝牙耳机录制声音

时间:2010-10-26 16:59:38

标签: android

我正在编写一个用于存储和管理语音备忘录的Android应用程序,其中包含一些基本的元数据和标记。录音时我用:

recorder = new MediaRecorder();         
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(currentRecordingFileName);
// and so on

这在以正常方式使用手机时效果很好。但是,即使插入耳机,它也无法检测到蓝牙耳机的存在,仍然使用手机自带的麦克风。

我也尝试使用MediaRecorder.AudioSource.DEFAULT,希望它会自动选择正确的源,但是根本没有录制声音。

我如何a)检测是否插入了蓝牙耳机和/或b)使用蓝牙耳机作为媒体记录器的音频源?

3 个答案:

答案 0 :(得分:9)

olivierg基本上是正确的(AudioSource仍然可以是MIC),一些基本代码看起来像这样:

    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    registerReceiver(new BroadcastReceiver() {

        @Override
        public 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) { 
                /* 
                 * Now the connection has been established to the bluetooth device. 
                 * Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
                 * new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                 * AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
                 *
                 * After finishing, don't forget to unregister this receiver and
                 * to stop the bluetooth connection with am.stopBluetoothSco();
                 */
                unregisterReceiver(this);
            }

        }
    }, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));

    Log.d(TAG, "starting bluetooth");
    am.startBluetoothSco();

我自己偶然发现了这一点,我想指出slott评论的重要性,包括正确的权限,最重要的是设置

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
清单文件中的

。如果没有它,您将不会收到任何错误消息,但状态将不会更改为已连接。

答案 1 :(得分:2)

根据文档,您需要使用AudioManager.startBluetoothSco()启动SCO音频连接,然后您似乎需要使用MediaRecorder.AudioSource.VOICE_CALL

据我所知,您无法选择特定设备等。这是在系统级执行的,即在用户将耳机与手机配对后。

修改

正如Stefan所说,AudioSource需要是MIC。

VOICE_CALL似乎不起作用。

答案 2 :(得分:0)

你可以detect connected bluetooth devices这样:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
    // Loop through paired devices
    for (BluetoothDevice device : pairedDevices) {
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}

但是,我不确定你是如何从耳机录制的,而不是常规MIC