当前位置: 首页 > 知识库问答 >
问题:

通过与Android设备配对的蓝牙耳机捕获音频

王鹏飞
2023-03-14

我正在尝试从与Android设备配对的蓝牙耳机中捕获音频。

以下是相关代码:

Intent in=null;
final int bufferSize=BufferElements2Rec*BytesPerElement;

final BroadcastReceiver brr=new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context,Intent intent)
    {
        int state=intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,-1);
        Log.d(labelApp,"Audio SCO State = "+state);
        if(AudioManager.SCO_AUDIO_STATE_CONNECTED==state)
        {
            Log.d(labelApp,"Entered and Starting Recording");
            //recorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT,
            //        RECORDER_SAMPLERATE, RECORDER_CHANNELS,
            //        RECORDER_AUDIO_ENCODING, bufferSize);
            recorder = new AudioRecord(android.media.MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, bufferSize);
            if(recorder==null)
            {
                Log.d(labelApp,"null");
            }
            else
            {
                Log.d(labelApp,"not null");
            }
            recorder.startRecording();
            recordingThread=new Thread(new Runnable()
            {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    writeAudioDataToFile();
                }

            },"AudioRecorder Thread");
            recordingThread.start();

            Log.d(labelApp,"Launched Recording Thread");
        }
    }
};

try
{
    Log.d(labelApp,"Initializing BT");
    am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    //am.setMode(AudioManager.MODE_IN_CALL);

    //in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
    //in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
    Log.d(labelApp,"Starting Bluetooth");
    am.setStreamSolo(AudioManager.MODE_IN_CALL, true);
    am.setBluetoothScoOn(true);
    am.setMode(AudioManager.MODE_IN_CALL);
    am.startBluetoothSco();
    Log.d(labelApp,"Can BT record from mic? "+am.isBluetoothScoAvailableOffCall());
    //in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
    in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));
    // The following line makes the audio go to hell
    //am.setMode(AudioManager.MODE_IN_CALL);


    //am.setStreamSolo(AudioManager.MODE_IN_CALL, true);
    Log.d(labelApp,"Everything initializated");
    Log.d(labelApp,"Recorder is...");
}
catch(Exception e)
{
    Log.e(labelApp,"exception",e);
    writeStack(e);
}

try
{
        Log.d(labelApp,"Initializing BT");
        am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        //am.setMode(AudioManager.MODE_IN_CALL);

        //in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
        //in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
        Log.d(labelApp,"Starting Bluetooth");
        am.setStreamSolo(AudioManager.MODE_IN_CALL, true);
        am.setBluetoothScoOn(true);
        am.setMode(AudioManager.MODE_IN_CALL);
        am.startBluetoothSco();
        Log.d(labelApp,"Can BT record from mic? "+am.isBluetoothScoAvailableOffCall());
        //in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
        in=registerReceiver(brr,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));
        // The following line makes the audio go to hell
        //am.setMode(AudioManager.MODE_IN_CALL);


        //am.setStreamSolo(AudioManager.MODE_IN_CALL, true);
        Log.d(labelApp,"Everything initializated");
        Log.d(labelApp,"Recorder is...");
}
catch(Exception e)
{
        Log.e(labelApp,"exception",e);
        writeStack(e);
}

清单要求权限:

  • WRITE_EXTERNAL_STORAGE
  • RECORD_AUDIO
  • 互联网
  • MODIFY_AUDIO_SETTINGS
  • BROADCAST_STICKY
  • 蓝牙
  • BLUETOOTH_ADMIN

每个应用程序的典型过滤LogCat输出是:

  1. 初始化BT
  2. 启动蓝牙
  3. BT可以从麦克风录音吗?true
  4. 一切初始化
  5. 录音机是...
  6. 音频SCO状态=2
  7. 音频SCO状态=1
  8. 进入并开始录制
  9. 不为空
  10. 启动录制线程

当am。startBluetoothSco();调用时,我可以听到BT设备上的短暂噪音,但随后该应用程序只是从Android设备的麦克风而不是BT的麦克风获取音频。

有没有关于我遗漏了什么/做错了什么的线索?

提前感谢您的关注

共有2个答案

归和惬
2023-03-14

蓝牙耳机的代码到语音录制

public class Recording {

static int count = 0;
static String Shared;
static String bFlag;
public static int TIMEOUT = 5000;
public static int COUNTDOWN_INTERVAL = 1000;
static Context context;

public static void checkAndRecord(Context context,
        OnBluetoothRecording BluetoothRecording, boolean resume) {

    // Check bluetooth flag And Bluetooth is ON or OFF
    if (getBluetoothFlag(context) && isBluetoothON()) {

        // Check for bluetooth and Record
        startBluetoothRecording(BluetoothRecording, resume, context);

    } else {

        // If Bluetooth is OFF Show Toast else Dont Show
        if (getBluetoothFlag(context) && !isBluetoothON()) {
            // false because recording not started
            Toast.makeText(context,
                    "Bluetooth is OFF. Recording from Phone MIC.",
                    Toast.LENGTH_SHORT).show();
            BluetoothRecording.onStartRecording(resume, false);
        } else {
            // false because recording not started
            BluetoothRecording.onStartRecording(resume, false);
        }
    }

}

private static void startBluetoothRecording(
        final OnBluetoothRecording BluetoothRecording,
        final boolean resume, Context context) {
    // TODO Auto-generated method stub

    final int MAX_ATTEPTS_TO_CONNECT = 3;
    final AudioManager audioManager = (AudioManager) context
            .getSystemService(Context.AUDIO_SERVICE);

    final CountDownTimer timer = getTimer(BluetoothRecording, audioManager,
            resume);

    context.registerReceiver(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            int state = intent.getIntExtra(
                    AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
            if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
                // cancel Timer
                timer.cancel();
                context.unregisterReceiver(this);

                // pass through and true because
                // recording from bluetooth so set 8000kHz

                BluetoothRecording.onStartRecording(resume, true);

            } else if (AudioManager.SCO_AUDIO_STATE_DISCONNECTED == state) {
                if (count > MAX_ATTEPTS_TO_CONNECT) {
                    context.unregisterReceiver(this);
                    // Stop BluetoothSCO
                    audioManager.stopBluetoothSco();
                    // reset Counter
                    count = 0;
                    // stop timer
                    timer.cancel();
                    // false because still recording not started
                    BluetoothRecording.onStartRecording(resume, false);
                } else {
                    // Increment Disconnect state Count
                    count++;

                }
            }

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

    // Start the timer
    timer.start();
    audioManager.startBluetoothSco();

}

// set the Timeout
private static CountDownTimer getTimer(
        final OnBluetoothRecording BluetoothRecording,
        final AudioManager audioManager, final boolean resume) {
    // TODO Auto-generated method stub
    return new CountDownTimer(TIMEOUT, COUNTDOWN_INTERVAL) {

        @Override
        public void onTick(long millisUntilFinished) {
            // Do Nothing

        }

        @Override
        public void onFinish() {

            // stopBluetoothSCO() and start Normal Recording
            audioManager.stopBluetoothSco();

            // false because recording button is already clicked but still
            // not recording.
            BluetoothRecording.onStartRecording(resume, false);
        }
    };
}

// Return's the bluetooth state
private static boolean isBluetoothON() {

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();
    return bluetoothAdapter.isEnabled();
}

// Return's the bluetoothFlag state
private static boolean getBluetoothFlag(Context context) {

    // shared pref
    SharedPreferences sp = context.getSharedPreferences(Shared,
            Context.MODE_PRIVATE);
    return sp.getBoolean(bFlag, false);

}

}
龙毅
2023-03-14

最重要的是,您需要设置

在清单文件中。没有它,将不会有错误消息,但B/T状态将拒绝更改为已连接。

其他相关权限包括:

<uses-permission android:name="android.permission.RECORD_AUDIO"/> 
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/> 
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>

编辑:除了评论之外,这里还有一些我以前使用过的示例代码:

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

brr(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();

此代码的学分归用户Stephan所有

 类似资料:
  • 我正在创建一个应用程序,需要显示连接的蓝牙耳机的名称。我的耳机已打开并连接到android设备。我正在将电话音频路由到耳机,但无法显示连接的耳机名称。 我尝试使用“ getName () ”方法,但它返回另一个当前未连接并已关闭的配对蓝牙移动设备。 非常需要建议。 更新 我使用了这段代码。但不幸的是,它返回了一个当前未连接的android蓝牙设备名称,我的耳机仍处于连接状态,我可以路由电话音频

  • 是否可以自动连接到蓝牙低能耗(BLE)设备? Android文档表明[](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context,boolean,android.bluetooth.BluetoothGattCallback)

  • 在某些Android设备中尝试在听筒上播放音频文件时似乎存在问题。预期的行为是它应该在听筒中播放音频文件,但在某些设备中,如三星Galaxy Note 2(Android版本4.4.2)和Sony Xperia XA(Android版本6.0),它通过扬声器播放它们。 然而,在摩托罗拉moto g(Android版本6.0)和nexus 5X(Android版本7.0)等设备中,它工作正常。 该应

  • 问题内容: 我正在创建一个应通过蓝牙连接到特定设备的应用程序。 无论设备是否已配对,我都希望我的应用程序与此设备连接。 现在我有这个 但是此功能仅连接到配对的设备。如果我的设备尚未配对,我想将其配对。不知道该怎么做。 有人可以给我任何建议吗? 问题答案: 首次请求权限。 然后使您的设备可发现: 然后创建一个 BroadcastReceiver 来监听系统中的动作: 并通过注册以下 Boardcas

  • 如果您想知道如何使用32英尺。NET库与蓝牙设备通信,请阅读解决方案 我目前正在尝试通过蓝牙在电脑和自建电脑之间进行通信。NET小工具原型。 Gadgeteer原型由主板、电源和蓝牙模块组成。模块处于可发现模式。 电脑上有一个基于32英尺的自定义蓝牙程序。NET Bluetooth正在运行。该程序检测范围内的所有蓝牙设备,并尝试与它们配对。然而,目前这并不是自动完成的,我必须输入设备的配对代码。

  • 我对同一主题进行了研究,发现android设备是a2dp源,音频只能从a2dp源流式传输到a2dp接收器。A2dp接收器可以是蓝牙耳机或蓝牙扬声器。 但我的问题是,Android应用程序“蓝牙音乐播放器”是如何工作的? 它允许从一部手机到另一部手机进行流媒体传输。因此,在这种情况下,收听移动设备必须充当接收器。这怎么可能?他们是否使用其他配置文件而不是a2dp? 好吧,这可能是他们使用的不同配置文