Question:
I searched already and this question has been asked before (here and replit.com/talk/ask/How-to-play-sounds-in-java/16589) but there has never been a proper response that solved it:
I’m looking to play audio (.wav or .au files). This code will run fine in something like Eclipse but in Replit I get the error:
Exception in thread "main" java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian is supported. at java.desktop/javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:425) at Play.playAudio(Play.java:28) at Play.main(Play.java:15)
Based on my understanding using SourceForge and other sources by using AudioFormat and DataLine, the clip should be converted to a playable format.
Repl link:
Replit
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
public class Play {
public static void main(String[] args) {
String audioFilePath = "jump.wav"; //"path_to_your_audio_file.wav"
playAudio(audioFilePath);
}
private static void playAudio(String filePath) {
try {
File audioFile = new File(filePath);
AudioInputStream stream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip)AudioSystem.getLine(info);
audioClip.open(stream);
System.out.println("playing sound");
audioClip.start();
}
catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
e.printStackTrace();
}
}
}