Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.IOException;
- import javax.sound.sampled.AudioSystem;
- import javax.sound.sampled.Clip;
- import javax.sound.sampled.LineUnavailableException;
- import javax.sound.sampled.UnsupportedAudioFileException;
- public class Sound{
- private Clip sound;
- public Sound(String location){
- try{
- sound = AudioSystem.getClip();
- File file = new File(location);
- sound.open(AudioSystem.getAudioInputStream(file));
- }
- catch(IOException | LineUnavailableException | UnsupportedAudioFileException error){
- System.out.println(error);
- }
- }
- public void play(){
- sound.start();
- }
- }
- File soundFile = new File( "something.wav" );
- AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( soundFile );
- clip = AudioSystem.getClip();
- clip.open(audioInputStream);
- clip.start();//This plays the audio
- private final int BUFFER_SIZE = 128000;
- private AudioInputStream audioStream;
- private SourceDataLine sourceLine;
- /**
- * @param filename the name of the file that is going to be played
- */
- public void playSound(String filename){
- try {
- audioStream = AudioSystem.getAudioInputStream(new File(filename));
- } catch (Exception e){
- e.printStackTrace();
- }
- try {
- sourceLine = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioStream.getFormat()));
- sourceLine.open(audioStream.getFormat());
- } catch (LineUnavailableException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- sourceLine.start();
- int nBytesRead = 0;
- byte[] abData = new byte[BUFFER_SIZE];
- while (nBytesRead != -1) {
- try {
- nBytesRead = audioStream.read(abData, 0, abData.length);
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (nBytesRead >= 0) {
- @SuppressWarnings("unused")
- int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
- }
- }
- sourceLine.drain();
- sourceLine.close();
- }
Add Comment
Please, Sign In to add comment