如何用Java播放声音?
时间:2020-03-05 18:42:53 来源:igfitidea点击:
我希望能够在程序中播放声音文件。我应该去哪里看?
解决方案
回答
一个不好的例子:
import sun.audio.*; //import the sun.audio package import java.io.*; //** add this into your application code as appropriate // Open an input stream to the audio file. InputStream in = new FileInputStream(Filename); // Create an AudioStream object from the input stream. AudioStream as = new AudioStream(in); // Use the static class member "player" from class AudioPlayer to play // clip. AudioPlayer.player.start(as); // Similarly, to stop the audio. AudioPlayer.player.stop(as);
回答
我写了下面的代码,效果很好。但是我认为它仅适用于.wav格式。
public static synchronized void playSound(final String url) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( Main.class.getResourceAsStream("/path/to/sounds/" + url)); clip.open(inputStream); clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start(); }
回答
Java教程的Sound Trail值得作为起点。
回答
除了导入在applet和应用程序中都可以使用的声音文件外,还有一种替代方法:将音频文件转换为.java文件,然后在代码中简单地使用它们。
我开发了一种工具,可以使此过程更加轻松。它大大简化了Java Sound API。
http://stephengware.com/projects/soundtoclass/