了解与Android的蓝牙耳机连接

时间:2013-03-15 21:10:57

标签: android bluetooth connection headset

我有蓝牙耳机(BTC6White)。我想谈谈麦克风和Android设备播放声音。

那么,我怎么能这样做?首先,我可以建立套接字连接

socket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString("0000111e-0000-1000-8000-00805f9b34fb"));
socket.connect();

然后,我如何获得音频?这个方法有什么用:startBuetoothSco?要将音频放入扬声器,我应该使用Auditrack吗?

int buffersize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_8BIT);
soundData = new byte [buffersize*5];    
audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 
   8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_8BIT, 
   soundData.length,AudioTrack.MODE_STREAM);

但是,那么,我应该填充缓冲区soundData吗?怎么样?使用套接字(进入线程)?

  mmInStream = socket.getInputStream();
  public void run() {
  byte[] buffer = new byte[8000*2]; 
      while (true) {
           bytes = mmInStream.read(buffer);
            audioTrack.write(buffer, 0, bytes); //write directly?
      }}

和startBuetoothSco()为什么?要知道sco状态吗? SCO_AUDIO_STATE_CONNECTED ...还是发送/接收数据?我不明白如何从de耳机获取音频数据,然后如何流式传输到扬声器。有必要建立一个SCO连接(用AudioManager)来获取蓝牙耳机的数据吗?

很难找到有关此问题的信息,而且android文档很差(本主题)。

1 个答案:

答案 0 :(得分:0)

用于检索音频数据,您可以设置流源。例如,如果您想通过蓝牙耳机录制声音,可以按如下方式初始化AudioRecord和AudioManager:

AudioRecord ar = new AudioRecord(MediaRecorder.AudioSource.MIC,
                    RECORDER_SAMPLERATE, 
                    RECORDER_OUT_CHANNELS,
                    RECORDER_AUDIO_ENCODING,
                    bufferSize);
ar.startRecording();

并致电

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

然后,您可以定义一个线程来读取您编写以下代码的音频数据:

private Runnable run_record = new Runnable(){

    @Override
    public void run() {
        // TODO Auto-generated method stub
        short dataBuf[] = new short[bufferSize];
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file_path);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while(isRecording){
            ar.read(dataBuf, 0, bufferSize);
            Log.d(LOG_TAG, "writing "+bufferSize+" bytes of data to file "+file_path);
            byte data[] = short2byte(dataBuf);
            try {
                os.write(data, 0, bufferSize);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }};

我希望我能清楚地解释清楚。