Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java resample .wav soundfile without third party library

Tags:

java

audio

wav

Is it possible to resample a .wav file from 22050 khz to 44100 khz in java without the use of any third party library?

Maybe using AudioInputStream?

edit: since it seems that without a third party library it isnt possible easily, what third party libraries do exist to accomplish a resampling?

like image 355
clamp Avatar asked Mar 14 '13 13:03

clamp


2 Answers

Since you are now accepting Third Party libraries, here is my suggestion

There are a lot of third party libraries that allows you to resample an audio wav file, For me, in my case(And I've recently used) the most user friendly third party library is Jave all you need to do is include the jar. no more tedious installation like other libraries

Jave has a method named

public void setSamplingRate(java.lang.Integer bitRate)

Which allows you to resample audio with the given bitrate.

like image 150
KyelJmD Avatar answered Nov 07 '22 00:11

KyelJmD


Its possible, quick and dirty. Just needs some diging in the javax.sound API:

import java.io.File;

import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import com.sun.media.sound.WaveFileReader;
import com.sun.media.sound.WaveFileWriter;

public class Resample {

public static void main(String[] argv) {
    try {
        File wavFile = new File("C:\\Temp\\test.wav");
        File dstFile = new File("C:\\Temp\\test_half.wav");
        WaveFileReader reader = new WaveFileReader();
        AudioInputStream audioIn = reader.getAudioInputStream(wavFile);
        AudioFormat srcFormat = audioIn.getFormat();

        AudioFormat dstFormat = new AudioFormat(srcFormat.getEncoding(),
                srcFormat.getSampleRate() / 2,
                srcFormat.getSampleSizeInBits(),
                srcFormat.getChannels(),
                srcFormat.getFrameSize(),
                srcFormat.getFrameRate() / 2,
                srcFormat.isBigEndian());

        AudioInputStream convertedIn = AudioSystem.getAudioInputStream(dstFormat, audioIn);

        WaveFileWriter writer = new WaveFileWriter();
        writer.write(convertedIn, Type.WAVE, dstFile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

}

This short hacked example will create a copy with halved sample rate of the file specified in the source. I think its pretty self explanatory.

like image 39
Durandal Avatar answered Nov 07 '22 02:11

Durandal