1

How can I play a .wav file in my Java application on Replit? I'm attempting to play a short audio clip after a JButton is clicked, but an exception is returned when I click the corresponding button. This is my code:

private void playAudio(String filepath) {
    final int BUFFER_SIZE = 128000;
    AudioInputStream audiostream;
    AudioFormat audioformat;
    SourceDataLine sourceline;
    try {
      audiostream = AudioSystem.getAudioInputStream(new File(filepath));
      audioformat = audiostream.getFormat();
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioformat);
      sourceline = (SourceDataLine) AudioSystem.getLine(info);
      sourceline.open(audioformat);
      sourceline.start();
      int bytesread = 0;
      byte[] abdata = new byte[BUFFER_SIZE];
      while (bytesread != -1) {
        bytesread = audiostream.read(abdata, 0, abdata.length);
        if (bytesread >= 0) {
          @SuppressWarnings("unused")
          int byteswritten = sourceline.write(abdata, 0, bytesread);
        }
      }
      sourceline.drain();
      sourceline.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

and it's called as:

playAudio("audio.wav");

The issue currently is that the program is returning an exception, and not playing audio:

java.lang.IllegalArgumentException: No line matching interface SourceDataLine supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian is supported.

I've tried converting the .wav file to the parameters specified in the exception, but to no avail. On Replit, I referenced an example that plays a .wav file successfully:

https://replit.com/@APCSA-21-22-Tan/Holiday-Song-APCSA-21-22-Tan-13

However, for some reason it isn't working for me, even if I download the corresponding packages present in the repl.

Is there a better/correct way to play audio specifically on Replit, or is it just an issue with my audio file? Thank you.

hangilk
  • 11
  • 3

0 Answers0