Java sound API
Java includes all the classes related to sound in javax.sound.sampled
package. For the below Example we need AudioSystem class- that is the
coordinator for Java Sound API. It includes all the required static
methods.
AudioSystem.getAudioInputStream(file or URL or inputStream) returns the
audio input stream that streams the audio data.
Second A clip object is required to playback the sound using start-stop
methods. Third You need a sound file in wav format.
Here is a simple java program example to play and stop the sound.
package program; import javax.sound.sampled.*; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { AudioInputStream ais = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/music.wav")); Clip clip = AudioSystem.getClip(); clip.open(ais); clip.start(); Scanner scanner = new Scanner(System.in); while (true) { String input = scanner.nextLine().strip().toUpperCase(); switch(input) { case "START": clip.start(); break; case "STOP": clip.stop(); break; case "RESTART": clip.setFramePosition(0); clip.start(); break; case "EXIT": clip.close(); System.exit(0); } } } }
Read also