Tue Jun 14, 2011 10:29 am
Tue Jun 14, 2011 12:56 pm
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sound;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class SoundExample extends Thread {
private String soundFile;
private Position postion;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
enum Position {
LEFT, RIGHT, NORMAL
};
public SoundExample(String wavfile) {
soundFile = wavfile;
postion = Position.NORMAL;
}
public SoundExample(String wavfile, Position p) {
soundFile = wavfile;
postion = p;
}
public void run() {
// here read sound from external file .
File fileObject = new File(this.soundFile);
if (!fileObject.exists()) {
System.err.println("Wave file not found: " + this.soundFile);
return;
}
AudioInputStream audioStream = null;
try {
audioStream = AudioSystem.getAudioInputStream(fileObject);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioStream.getFormat();
SourceDataLine srcDataLine = null;
DataLine.Info infoObject = new DataLine.Info(SourceDataLine.class, format);
try {
srcDataLine = (SourceDataLine) AudioSystem.getLine(infoObject);
srcDataLine.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (srcDataLine.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) srcDataLine
.getControl(FloatControl.Type.PAN);
if (postion == Position.RIGHT)
pan.setValue(1.0f);
else if (postion == Position.LEFT)
pan.setValue(-1.0f);
}
srcDataLine.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
srcDataLine.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
srcDataLine.drain();
srcDataLine.close();
}
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.