Record Audio and save to wave file format

Anything libgdx related goes here!

Record Audio and save to wave file format

Postby xpdt » Wed Nov 14, 2018 11:23 am

Hi
The following code works well for recording audio and playback with very good quality (3 seconds):
Code: Select all
        final int samples = 22050;
        boolean isMono = true;
        final short[] data = new short[samples*3];

        final AudioRecorder recorder = Gdx.audio.newAudioRecorder(samples, isMono);
        final AudioDevice player = Gdx.audio.newAudioDevice(samples, isMono);

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Record: Start");
                recorder.read(data, 0, data.length);
                recorder.dispose();
                System.out.println("Record: End");
         
                System.out.println("Play : Start");
                player.writeSamples(data, 0, data.length);
                System.out.println("Play : End");
                player.dispose();
            }
        }).start();


I try to save the sound in the Wav format using the code below:
Code: Select all
    OutputStream out = new FileOutputStream("d:\\test.wav");
    PCMtoFile(out, data, samples, 1, 16);


But the sound stored in the file has a strong noise and is very poor quality :?

( PCMtoFile source code: https://stackoverflow.com/questions/4440015/java-pcm-to-wav?answertab=votes#tab-top )
xpdt
 
Posts: 33
Joined: Mon Jul 04, 2016 2:29 am

Re: Record Audio and save to wave file format

Postby evilentity » Wed Nov 14, 2018 2:20 pm

Probably the random copy pasted code doesnt quite work, if something is not quite right in the wav it will sound messed up.
Looking for a freelancer? PM me!
evilentity
 
Posts: 4555
Joined: Wed Aug 24, 2011 11:37 am

Re: Record Audio and save to wave file format

Postby xpdt » Wed Nov 14, 2018 4:31 pm

evilentity wrote:Probably the random copy pasted code doesnt quite work, if something is not quite right in the wav it will sound messed up.

The problem was from "get16bitmap" method.
After using the following code for convert short to byte, the problem was resolved.
Code: Select all
        byte[] data = new byte[pcmdata.length * 2]; //create a byte array to hold the data passed (short = 2 bytes)
        ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(pcmdata); // cast a short array to byte array


Thanks
xpdt
 
Posts: 33
Joined: Mon Jul 04, 2016 2:29 am


Return to Libgdx

Who is online

Users browsing this forum: Bing [Bot], Majestic-12 [Bot] and 1 guest