Java:连续录制音频并保存最后一部分

时间:2019-02-03 14:47:41

标签: java android audio audio-recording

我要连续录制音频,并且当用户按下按钮时,保存录制的音频的最后4秒钟。

我使用this link录制音频,但目前面临的问题是:

  • 我不知道可以录制多长时间。
  • 短数组或字节数组已满时会发生什么。
  • 如何仅保存最后记录的4秒。

我当前录制音频的代码:

private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder;
    private boolean isRecording = false;
    private int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    private short sData[];

    public short[] getRocordingShort(){
        return sData;
    }

    public byte[] getRocordingByte(){
        return short2byte(sData);
    }

    public Recorder(){
        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * 2);// 2 bytes in 16bit format
    }

    public void startRecording() {
        sData = new short[BufferElements2Rec];
        recorder.startRecording();
        isRecording = true;
        Thread recordingThread = new Thread(new Runnable() {
            public void run() {
                while (isRecording) {
                    // gets the voice output from microphone to byte format
                    recorder.read(sData, 0, BufferElements2Rec);
                }
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

    //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    public void stopRecording() {
        // stops the recording activity
        if (recorder != null) {
            isRecording = false;
            recorder.stop();
            /*recorder.release();
            recorder = null;
            recordingThread = null;*/
        }
    }

0 个答案:

没有答案