Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

sound file java

import javax.sound.sampled.*;
import java.io.IOException;
import java.io.File;//what we need to import

public class Main{//what we need to put in the "Main class"
	public static void main(String[] args) throws InterruptedException, LineUnavailableException, IOException, UnsupportedAudioFileException { //mainmethod with exeptions
  		String thePath = "*Path*"; //insert the audiofile here
  		SoundPlayer player = new SoundPlayer();
  		player.play(thePath);
	}
}

public class SoundPlayer {//new class where the sounfile will be started and ended
    private static final int BUFFER = 4096;

    void play(String filePath) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        File soundFile = new File(filePath);
      	AudioInputStream Stream = AudioSystem.getAudioInputStream(soundFile);
      	AudioFormat formatAudio = Stream.getFormat();
      	DataLine.Info info = new DataLine.Info(SourceDataLine.class, formatAudio);
      	SourceDataLine Audio = (SourceDataLine) AudioSystem.getLine(info);
      	Audio.open(formatAudio);
      	Audio.start();
      	byte[] buffer = new byte[BUFFER];
      	int readBytes = -1;

      	while ((readBytes = Stream.read(buffer)) != -1) {
          	Audio.write(buffer, 0, readBytes);
        }

      	Audio.drain();
      	Audio.close();
        Stream.close();
    }
}
//If I was able to help you I would be happy about a Donation
 
PREVIOUS NEXT
Tagged: #sound #file #java
ADD COMMENT
Topic
Name
2+4 =