简体   繁体   中英

How to play a wav file using Java?

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

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);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM