0

I am attempting to learn how to play an audio file and came up with the code below. There are no errors and I put in a path for a .wav file, but the sound file does not play. How can I fix this?

    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;

    public class RunPlayer {

        public void runner(String audioFilePath) throws UnsupportedAudioFileException, IOException, LineUnavailableException { 
            File audioFile = new File(audioFilePath);

            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

            AudioFormat format = audioStream.getFormat();

            DataLine.Info info = new DataLine.Info(Clip.class, format);

            Clip audioClip = (Clip) AudioSystem.getLine(info);

            audioClip.open(audioStream);
            audioClip.start();

            audioClip.close();
            audioStream.close();
        }

        public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
            RunPlayer run = new RunPlayer();
            run.runner("thefilepathIentered");
        }

   }
corecase
  • 1,278
  • 5
  • 18
  • 29
user3370908
  • 29
  • 1
  • 7

1 Answers1

0

The problem must be the fact that you're closing the audioClip and audioStream immediately after you start the clip.

You want the clip to run, and then probably have some sort of button or function that will close the clip once it has finished playing.

Take a look at this SO answer: https://stackoverflow.com/a/11025384/815086

corecase
  • 1,278
  • 5
  • 18
  • 29