Immediate Audio Input & Output Android

前端 未结 4 1196
感情败类
感情败类 2021-02-18 16:43

In my Android App, I would like to take in some audio from the mic of the smartphone and play it immediately, live, like a microphone, with no lag. I am currently thinking of us

4条回答
  •  盖世英雄少女心
    2021-02-18 17:17

    try this. I have not run this.

          recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
          RECORDER_SAMPLERATE, RECORDER_CHANNELS,
          RECORDER_AUDIO_ENCODING, bufferSize * BytesPerElement);
    
        recorder.startRecording();
    
        isRecording = true;
    
        recordingThread = new Thread(new Runnable() {
    
         public void run() {
    
          try {
              int intSize = android.media.AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_MONO , RECORDER_AUDIO_ENCODING);
              byte[] sData = new byte[bufferSize];
              AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, AudioFormat.CHANNEL_OUT_MONO, RECORDER_AUDIO_ENCODING, intSize, AudioTrack.MODE_STREAM);
              while(isRecording){
              recorder.read(sData, 0, bufferSize);  //isRecording = false; onStop button
    
              if (at!=null) { 
                  at.play();
                  // Write the byte array to the track
                  at.write(sData, 0, sData.length); 
                  at.stop();
                  at.release();
              }
              }
        } catch (IOException e) {
            e.printStackTrace();
        }
     }
      }, "AudioRecorder Thread");
        recordingThread.start();
    

提交回复
热议问题