Change The Pitch Of Audio Using Java Sound API

What is Audio ?

Audio is a sound which is audible to human ear. Audio can be represented as an electronic frequency range of 20 to 20,000 Hz that generate audible sound. Audio is generated in Analog waveform format but in computer it is stored as digital format. Computers use ADC (Analog to Digital Converter) for converting Analog audio format into digital format.

Generally Audio is stored into compressed format like WAV, MP3, OGG, AIFF, etc. when user plays audio of any format then that audio is played via audio stream like byte by byte data streaming.

What is Pitch of Audio?

Pitch is the frequency representation of sound. Every Audio is played in particular pitch like human sound pitch is different than animal sound pitch. All the sounds have different frequency levels or pitch. One audio can be heard in different pitch if the audio is played on different frequency level.

For example, if we play one song with original frequency of 441 Hz on 25,000 Hz frequency then that song will be played on different pitch.

How Java Sound API is used for changing the pitch of audio?

Java Sound API is one of the media API which is used for sound operations like storing, manipulating, editing sounds.

Step 1 : Get source & destination files’ path & file objects

Java

1

2

3

4

//source file

finalFile file1=newFile(“Sample.mp3”);

//destination file

finalFile file2=newFile(“Sample_cat.wav”);

Step 2 : Get Audio stream of that audio source file

Java

1

2

//audio stream of file1

finalAudioInputStream in1=getAudioInputStream(file1);

Step 3 : Get Audio format for required pitch

For example, here we are changing the pitch into cat sound then we are changing frequency level from 44100 Hz to 72000 Hz.

Java

1

2

3

4

5

6

7

8

9

//get audio format for targetted sound

finalAudioFormat inFormat=getOutFormat(in1.getFormat());

//change the frequency of Audio format

privateAudioFormat getOutFormat(AudioFormat inFormat){

intch=inFormat.getChannels();

floatrate=inFormat.getSampleRate();

returnnewAudioFormat(PCM_SIGNED,72000,16,ch,ch*2,rate,

inFormat.isBigEndian());

}

Step 4 : Save that formatted file into target file format

Java

1

2

3

4

//get the target file audio stream using file format

finalAudioInputStream in2=getAudioInputStream(inFormat,in1);

//write the audio file in targeted pitch file

AudioSystem.write(in2,AudioFileFormat.Type.WAVE,file2);

Lets see now how to generate different sound effects on audio using Java Sound API.