I'm looking for information on how I can increase the playback speed of a sound file using Java and it's sound API.
I'm currently using a clip and an AudioInputStream to play back the file, but I'll be glad to change that if it means I can increase the playback speed.
I do this by using linear interpolation. As you step through your samples by some increment, use the fractional distance to create a value to stream.
For example if you land at 1.25 (between a sample with value 10 and sample of value 30), you would output a value of 15.
A crude way to play back at an integral number (2,3,4..) of times the original speed, is to skip every so many samples of the original input stream. E.G. For double speed, skip one out of two, for triple speed, skip 2 out of 3.
import javax.swing.JOptionPane;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.util.Date;
class AcceleratePlayback {
public static void main(String[] args) throws Exception {
int playBackSpeed = 1;
if (args.length>0) {
try {
playBackSpeed = Integer.parseInt(args[0]);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int skip = playBackSpeed-1;
System.out.println("Playback Rate: " + playBackSpeed);
URL url = new URL("http://pscode.org/media/leftright.wav");
System.out.println("URL: " + url);
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
AudioFormat af = ais.getFormat();
int frameSize = af.getFrameSize();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[2^16];
int read = 1;
while( read>-1 ) {
read = ais.read(b);
if (read>0) {
baos.write(b, 0, read);
}
}
System.out.println("End entire: \t" + new Date());
byte[] b1 = baos.toByteArray();
byte[] b2 = new byte[b1.length/playBackSpeed];
for (int ii=0; ii<b2.length/frameSize; ii++) {
for (int jj=0; jj<frameSize; jj++) {
b2[(ii*frameSize)+jj] = b1[(ii*frameSize*playBackSpeed)+jj];
}
}
System.out.println("End sub-sample: \t" + new Date());
ByteArrayInputStream bais = new ByteArrayInputStream(b2);
AudioInputStream aisAccelerated =
new AudioInputStream(bais, af, b2.length);
Clip clip = AudioSystem.getClip();
clip.open(aisAccelerated);
clip.loop(2*playBackSpeed);
clip.start();
JOptionPane.showMessageDialog(null, "Exit?");
}
}
prompt> java AcceleratePlayback
Playback Rate: 1
URL: http://pscode.org/media/leftright.wav
End entire: Mon Apr 25 20:54:55 EST 2011
End sub-sample: Mon Apr 25 20:54:55 EST 2011
prompt> java AcceleratePlayback 2
Playback Rate: 2
URL: http://pscode.org/media/leftright.wav
End entire: Mon Apr 25 20:55:20 EST 2011
End sub-sample: Mon Apr 25 20:55:20 EST 2011
prompt> java AcceleratePlayback 3
Playback Rate: 3
URL: http://pscode.org/media/leftright.wav
End entire: Mon Apr 25 20:55:36 EST 2011
End sub-sample: Mon Apr 25 20:55:36 EST 2011
prompt>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With