简体   繁体   English

如何使用Java播放wav文件?

[英]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. 我想播放一个wav文件,在谷歌搜索后我发现了这个脚本,但它不起作用。 (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. 只需从代码中删除while循环即可修复。 The while loop is making the thread sleep so it can't play the audio file. while循环使线程休眠,因此无法播放音频文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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