Reputation: 115
How do you change the sample rate of an audio file? In my app I append multiple audio files in .wav
format which have a sample rate of 24,000 Hz and I want to convert the resulting file's sample rate to 20,050 Hz. I tried creating a new AudioFormat
and setting the sample rate to 20,050 Hz like this:
appendedFiles = new AudioInputStream(
new SequenceInputStream(appendedFiles, clip),
new AudioFormat(appendedFiles.getFormat().getEncoding(),
20050,
appendedFiles.getFormat().getSampleSizeInBits(),
appendedFiles.getFormat().getChannels(),
appendedFiles.getFormat().getFrameSize(),
appendedFiles.getFormat().getFrameRate(),
appendedFiles.getFormat().isBigEndian()
),
appendedFiles.getFrameLength() + clip.getFrameLength());
but this doesn't completely work, it slows down the audio and thickens the voice.
Upvotes: 1
Views: 1532
Reputation: 5310
You cannot just change the sample rate, you must also change the frame rate, which for .wav
(and I guess all uncompressed audio formats) are identical. So the first thing you need to do is to set both the target sample and frame rate.
The second thing you should do is involve the javax.sound.sampled.AudioSystem. It's the central class in Javasound and must not be ignored.
Using AudioSystem
, you can do something like this (untested code):
float targetRate = 20050;
// source audio format, you seem to assume
// it's the same for all files
AudioFormat sourceFormat = appendedFiles.getFormat();
// create an AudioInputStream for your two audio streams
AudioInputStream sourceStream = AudioSystem.getAudioInputStream(
new SequenceInputStream(appendedFiles, clip)
);
// construct the target format with the sample/frame rate
AudioFormat targetFormat = new AudioFormat(
appendedFiles.getFormat().getEncoding(),
targetRate,
sourceFormat.getSampleSizeInBits(),
sourceFormat.getChannels(),
sourceFormat.getFrameSize(),
targetRate,
sourceFormat.isBigEndian());
// let the AudioSystem resample your concatenated streams
resampledInputStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
But there is one caveat! The AudioSystem
may not support the resampling factor you want. In that case you need to install a suitable service provider. For Windows or Mac (currently x86 only), you could use FFsampledSP, which supports resampling with FFmpeg as backend (full disclosure, I am the author). Perhaps there are other, more suitable resampler for your platform.
If everything fails, I would consider using command line tools like SOX or FFmpeg.
Upvotes: 1