Java操作應(yīng)用——使用Java播放音頻
在Java中,播放音頻是一個(gè)很常見(jiàn)的需求,尤其是在游戲開(kāi)發(fā)里面。
下面這個(gè)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(); } } |
點(diǎn)擊加載更多評(píng)論>>