Java操作应用——使用Java播放音频
在Java中,播放音频是一个很常见的需求,尤其是在游戏开发里面。
下面这个DEMO演示了如何在Java中播放音频。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.io.*; import java.net.URL; import javax.sound.sampled.*; import javax.swing.*; // To play sound using Clip, the process need to be alive. // Hence, we use a Swing application. public class playSoundDemo extends JFrame { // Constructor public playSoundDemo() { this .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this .setTitle( "Play Sound Demo" ); this .setSize( 300 , 200 ); this .setVisible( true ); try { URL url = this .getClass().getResource( "MyAudio.wav" ); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } } public static void main(String[] args) { new playSoundDemo(); } } |
点击加载更多评论>>