Search code examples
javaandroidaudiorecordandroid-mediarecorder

How to extract part of recorded audio bytes


I recording sound to byte array, see below:

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    recorder.setAudioSamplingRate(44100);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setAudioEncodingBitRate(1024*1024);

...

    while (hasRecording) {
        try {
            int read = inputStream.read(data, 0, data.length);
            if (read == -1)
                break;

            byteArrayOutputStream.write(data, 0, read);
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

By recording I am drawing amplitude to chart (on the fly). After stop recording user can select part of chart. And now, how can I extract part of byte array by the user selection? I have only position selected coords and byte array of completed recorded sound. I know, that I have to calculate with bitrate for gets position in byte array, but I don't know how.

Thanks.


Solution

  • Are you able to determine the number of bytes per frame? I can see that you have 44100 frames per second. But I don't usually work with audio in terms of bit rates and am not clear what that relates to.

    In a pure Java context, the AudioFormat is defined in terms of the bits used for encoding, with 16 bits (two bytes) being the most common, and the number of channels, e.g., 1 channel for mono, 2 channels for stereo.

    With what is known as the common "CD Quality" format, we have 16-bit encoding and stereo, thus 4 bytes per frame. From that and the frame rate, it is a simple matter to correlate a specific byte to a moment in time.