1

I am trying to write Short[] to wav audio file using file output stream but the file only contains scratch sound. The reason i am using short[] rather than byte[] is because i am trying to use an external library which provides Voice Activity Detection . I did add wav header provided in Android Audio Record to wav and i tried to convert Short[] to byte[] using Converting Short array from Audio Record to Byte array without degrading audio quality? but none of the above links were able to help me. Here is my code:

private class ProcessVoice implements Runnable {

    @Override
    public void run() {
        File fl = new File(filePath, AUDIO_RECORDING_FILE_NAME);
        try {
            os = new BufferedOutputStream(new FileOutputStream(fl));
        } catch (FileNotFoundException e) {
            Log.w(TAG, "File not found for recording ");
        }
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);

        while (!Thread.interrupted() && isListening && audioRecord != null) {
            short[] buffer = new short[vad.getConfig().getFrameSize().getValue() * getNumberOfChannels() * 2];
            audioRecord.read(buffer, 0, buffer.length);

            isSpeechDetected(buffer);
        }
    }


    private void isSpeechDetected(final short[] buffer) {
        vad.isContinuousSpeech(buffer, new VadListener() {

            @Override
            public void onSpeechDetected() {
                callback.onSpeechDetected();
                bytes2 = new byte[buffer.length * 2];
                ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(buffer);
                //Log.w(TAG, String.valueOf(buffer));
                try {
                    // // writes the data to file from buffer
                    // // stores the voice buffer
                    os.write(header, 0, 44);
                    working = true;
                    os.write(bytes2, 0, bytes2.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoiseDetected() {
                callback.onNoiseDetected();
                if(working == true){
                    working = false;
                    try {
                        doneRec();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //Log.w(TAG, String.valueOf(bytes2));
            }

        });
    }
}
  • Did you solve this question already? If you still need help: WAV-files are encoded audio files, meaning the solution would probably be to either encode the audio or store it as a RAW audio file – Distjubo May 05 '20 at 11:05
  • Also consider moving the `new short[...]` outside of the loop. Otherwise you're putting unnecessary pressure on the GC – Distjubo May 05 '20 at 11:07

0 Answers0