I'm following this Java tutorial, and I've come across how to play audio, I followed the exact steps to writing the code, however, despite this, I get an error message, I doubt the video is out of date considering it's only a month old, so I'm not sure what the problem is.
Here's the code I've written:
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException, UnsupportedAudioFileException, LineUnavailableException
{
Scanner sc = new Scanner(System.in);
File file = new File("bababooey.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
String response = sc.next();
}
}
Here's the error message I keep getting:
"C:\Program Files\AdoptOpenJDK\jdk-15.0.1.9-hotspot\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.4\lib\idea_rt.jar=57472:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\1ando\Documents\Programming\Java\Complete Java Tutorial\Audio\out\production\Audio" Main
Exception in thread "main" java.lang.IllegalArgumentException: Audio data < 0
at java.desktop/com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1086)
at Main.main(Main.java:12)
Process finished with exit code 1
I'd really appreciate a response, thanks
Other than the fact you are missing try/catch to trap any exceptions, your code works for me.
Check your imports for AudioInputStream, AudioSystem, Clip, LineUnavailableException, and finally the UnsupportedAudioFileException. All these classes should be part of the javax.sound.sampled Package. Imports should be:
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;
The code could be something like this:
// Scanner sc = new Scanner(System.in); // I don't understand why you are using Scanner!
AudioInputStream audioStream = null;
try {
File file = new File("explosion.wav");
audioStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
//String response = sc.next(); // I don't understand why you are using Scanner!
}
catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
System.err.println(ex);
}
finally {
try {
if (audioStream != null) {
audioStream.close();
}
}
catch (IOException ex) {
System.err.println(ex);
}
}