1

I would like to play a wav file and after I googled it I found this script but it doesn't work. (It didn't throw any exceptions nor have compiling problems)

 import java.io.File;
 import films.Film;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.Clip;

 public class MusicStorage {

 /**
 * Opens a wav file and plays it
 * @param args
 */
public void play(Film song) {
    try {
        Clip sound = AudioSystem.getClip();

        sound.open(AudioSystem.getAudioInputStream(new File(song.getClip())));

        sound.start();

        while (sound.isRunning())
            Thread.sleep(1000);

        sound.close();
    } catch (Exception e) {
        System.out.println("Whatever" + e);
    }
  }
}

import audio.MusicStorage;
import films.Film;

public class Aplication {

private static Film gladiator = new Film("Gladiator", "gladiator.wav");
private static MusicStorage storage = new MusicStorage();

public static void main(String[] args) {
    storage.play(gladiator);
}
}

public class Film {

private String name;
private String clip;

public Film(String name, String clip) {
    this.name = name;
    this.clip = clip;
}

public String getClip() {
    return clip;
}

public String getName() {
    return name;
}
}

I have added all the code that I have so I hope it would be clear to solve my problem

FAYA
  • 137
  • 1
  • 11

1 Answers1

1

Just remove the while loop from your code and it should be fixed. The while loop is making the thread sleep so it can't play the audio file.

public void play(Film song) {
    try {
        Clip sound = AudioSystem.getClip();

        sound.open(AudioSystem.getAudioInputStream(new File(song.getClip())));

        sound.start();

    } catch (Exception e) {
        System.out.println("Whatever" + e);
    }
  }
}
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59