javaaudioaudio-converter

Java convert audio from 44.1 kHz to 48 kHz


I am currently having a bit of trouble converting an AudioInputStream from MPEG1L3, 44.1 kHz, stereo with unknown bits per sample, unknown frame size and unknown frame rate to 48KHz 16bit stereo signed BigEndian PCM.

I already tried just converting it by using

AudioSystem.getAudioInputStream(new AudioFormat(Encoding.PCM_SIGNED, 48000, 16, 2, 4, 48000, true), in);

but it always gives me this error:

java.lang.IllegalArgumentException: Unsupported conversion: PCM_SIGNED 48000.0 Hz, 16 bit, stereo, 4 bytes/frame, big-endian from MPEG1L3 44100.0 Hz, unknown bits per sample, stereo, unknown frame size, unknown frame rate,
        at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:894)
        at me.joastuart.bot.audio.GetStreamTP.lambda$0(GetStreamTP.java:23)
        at java.base/java.lang.Thread.run(Thread.java:829)

Sadly I can't change the final nor the input AudioFormat.

I hope you can me to solve this issue!

~JoaStuart


Solution

  • AFAIK, Java doesn't support formats with a frame rate greater than 44100 fps. Has that changed with the latest versions?

    It's possible to extract PCM using an AudioInputStream, and convert the PCM to the higher rate. The process would be similar to playing back a file at a slightly faster speed, making use of linear interpolation to obtain the data values that lie "in between" the existing PCM frames. From there, converting the PCM to bytes in the correct order can be done (there are other stackoverflow posts on converting PCM to bytes).

    But I don't know how to save the byte array as a playable wav where the wav header indicates the 48000 frame rate. I've only saved wavs in formats supported by Java and have not had to deal with wav headers since that is usually handled by AudioSystem.write method.