I am trying to add sound in program. I have no experience how to add sound in program.
I am trying this but this code giving me exception “null”. I don’t know what argument I have to pass in playSound function. So help me please.
import java.io.InputStream;
import sun.audio.*; //import the sun.audio package
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class Main {
public Main() {
}
public static void main(String[] args) {
System.out.println("hello there");
playSound("Hi there");
}
public static synchronized void playSound(final String url) {
new Thread(new Runnable() { // the wrapper thread is unnecessary, unless
// it blocks on the Clip finishing, see
// comments
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem
.getAudioInputStream(Main.class
.getResourceAsStream("pacman_chomp.wav"
+ url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
}
Since you said your playSound method didn’t work, here’s a sound class I coded.
And here’s how it’s called: