Запись с BluetoothHeadset Mic - PullRequest
       41

Запись с BluetoothHeadset Mic

0 голосов
/ 18 ноября 2018

Привет,

Я пытаюсь создать приложение с Android-Studio, которое может записывать звук с помощью Bluetooth-HS.Я знаю, что есть много постов, близких к этому, но я попробовал все ответы, и это не будет работать для меня.Мой код возвращает мне заполненный байтовый буфер, однако, как показывает тестирование, это всегда микрофон для телефона, а не микрофон для гарнитуры.Если бы кто-нибудь мог взглянуть на мой код и указать, почему он не использует BT-HS, это было бы для меня огромной помощью.

public class Inhalation extends AppCompatActivity {
    AudioManager audioManager;
    AudioRecord audioRecord=null;
    Button mrecord;
    Button mpause;
    boolean isRecording=false;
    private Thread recordingThread = null;
    private int bufferSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inhalation);
        mrecord= findViewById(R.id.Button_Record_ID);
        mpause=findViewById(R.id.Button_Pause_ID);
        audioManager =(AudioManager) this.getSystemService(this.AUDIO_SERVICE);
    }
    //is supposed to start recording using the BT MIC. Can only be called if BTSCO is connected
    private void startRecording() {

            audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
            audioRecord.startRecording();
            isRecording = true;
            recordingThread = new Thread(new Runnable() {
                public void run() {
                    writeAudioDataToFile();
                }
            }, "AudioRecorder Thread");
            recordingThread.start();

        }
        //picks up the recorded audiobuffer and writes it into a file
    private void writeAudioDataToFile() {

        String filename="record";
        byte saudioBuffer[] = new byte[bufferSize];
        FileOutputStream os = null;

        // TODO (4) Audiorecord Filecreation
        try {
            os = openFileOutput(filename, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("headset_rec","false filepath");
        }

        while (isRecording) {

            audioRecord.read(saudioBuffer, 0, bufferSize);
            try {
                os.write(saudioBuffer, 0, bufferSize);
              //  os.write(saudioBuffer);
                Log.d("headset_rec","writing"+saudioBuffer[0]);
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("headset_rec","writefail");
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            Log.d("headset_rec","close");
            e.printStackTrace();
        }

    }
    //stops the recording
    private void stopRecording() {
        // stops the recording activity
        if (null != audioRecord) {
            isRecording = false;
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            recordingThread = null;
        }
    }
    public void Record_On_Click(View view){
            mpause.setEnabled(true);
            mrecord.setEnabled(false);
        requestRecordAudioPermission();
        startRecording();
    }

    //Button to pause
    public void Record_Pause_Click(View view){
        stopRecording();
     //   readFromFile();
            mrecord.setEnabled(true);
            mpause.setEnabled(false);
    }

    //if BluetoothSCO is connected enables recording
    private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
            System.out.println("ANDROID Audio SCO state: " + state);
            if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
                Log.d("SCOO","connected");
                mrecord.setEnabled(true);
            }
            if(AudioManager.SCO_AUDIO_STATE_DISCONNECTED==state){
                Log.d("SCOO","disconnected");
                mrecord.setEnabled(false);
            }
        }
    };

    //connects to the bluetoothHeadset doing the following:
    @Override
    protected void onResume() {
        // TODO (5) Bluetooth Mik
        // Start Bluetooth SCO.
        if(isRecording){
            mpause.setEnabled(true);
            mrecord.setEnabled(false);
        }
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        registerReceiver(mBluetoothScoReceiver, intentFilter);
        audioManager.setMode(audioManager.MODE_NORMAL);
        audioManager.setBluetoothScoOn(true);
        audioManager.startBluetoothSco();
        // Stop Speaker.
        audioManager.setSpeakerphoneOn(false);
        super.onResume();
    }

    //Disconnects from the Bluetoothheadset doing the following
    @Override
    protected void onDestroy() {

        audioManager.stopBluetoothSco();
        audioManager.setMode(audioManager.MODE_NORMAL);
        audioManager.setBluetoothScoOn(false);
        // Start Speaker.
        audioManager.setSpeakerphoneOn(true);
        unregisterReceiver(mBluetoothScoReceiver);
        super.onDestroy();
    }
    private void requestRecordAudioPermission() {//gets the permission to record audio
        //check API version, do nothing if API version < 23!
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                Log.d("Activity_Request", "Wastn granted!");
                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                    Log.d("Activity_Request", "request!");
                    // Show an expanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.
                    Log.d("Activity_Request", "take!");
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
                }
            }
        }
    }
...