Issue
I am sure that the file name is right! So what is the problem in AudioSystem.getAudioInputStream
?
public class Main {
public static void main(String[] args) {
public static Clip clip;
AudioInputStream audioStream = null;
try {
//URL soundUrl = Main.class.getResource("D:/eclipse/workplace/AudioTestAPI/2.mp3");
URL soundUrl = Main.class.getResource("D:/eclipse/workplace/AudioTestAPI/3.wav");
audioStream = AudioSystem.getAudioInputStream(soundUrl);//42
clip.open(audioStream);
} catch(LineUnavailableException e) {
e.printStackTrace();
} catch(UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch(IOException eo) {
eo.printStackTrace();
}
clip.start();
do {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while(clip.isActive());
}
}
Result:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1032)
at Main.main(Main.java:42)
Solution
The java.lang.NullPointerException
occurs because your variable soundUrl
is null
.
Try this:
File file = new File("D:/eclipse/workplace/AudioTestAPI/3.wav");
audioStream = AudioSystem.getAudioInputStream(file);
Let me know what happened after my suggestion.
Edited:
package com.acme.audio;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Main {
public static void main(String[] args) throws LineUnavailableException {
Clip clip = AudioSystem.getClip();
AudioInputStream audioStream = null;
try {
File file = new File("D:/eclipse/workplace/AudioTestAPI/3.wav");
audioStream = AudioSystem.getAudioInputStream(file);
clip.open(audioStream);
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
} catch (IOException eo) {
eo.printStackTrace();
}
clip.start();
do {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (clip.isActive());
}
}
Answered By - João Zarate
Answer Checked By - Senaida (JavaFixing Volunteer)