windows播放wav声音文件--java播放wav完整demo

来源:互联网 发布:Js button 非活性 编辑:程序博客网 时间:2024/05/01 01:45
有个新的需求,要java的windows应用发声音,原本说的只是使用蜂鸣器发声音,直接上代码:
public static void main(String[] args) {        Toolkit toolkit = Toolkit.getDefaultToolkit();        toolkit.beep();     }
但是蜂鸣器发的声音很单一,而且没办法更换,后来就写了一个例子,直接播放wav格式的声音文件,这个就好多了,可以直接播放。直接上代码了:
package test;import java.io.BufferedInputStream;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineEvent;import javax.sound.sampled.LineListener;import javax.sound.sampled.LineEvent.Type;public class TestBeep {    public static void main(String[] args) {        try {            TestBeep beep = new TestBeep();            AudioInputStream inputStream = beep.getAudioStream();            beep.play(inputStream);            Thread.sleep(1000);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    private AudioInputStream getAudioStream() throws Exception{        return AudioSystem        .getAudioInputStream(new BufferedInputStream(getClass()                .getResourceAsStream("/message.wav")));    }    private void play(AudioInputStream audioInputStream) throws Exception{        Clip clip = AudioSystem.getClip();        AudioListener listener = new AudioListener();        clip.addLineListener(listener);        clip.open(audioInputStream);        try {            clip.start();            listener.waitUntilDone();        } catch (final InterruptedException e) {            e.printStackTrace();        } finally {            clip.close();        }        audioInputStream.close();    }    class AudioListener implements LineListener {        private boolean done = false;        /**         * This method allows to be notified for each event while playing a         * sound         */        @Override        public synchronized void update(final LineEvent event) {            final Type eventType = event.getType();            if (eventType == Type.STOP || eventType == Type.CLOSE) {                done = true;                notifyAll();            }        }        /**         * This method allows to wait until a sound is completly played         *          * @throws InterruptedException         *             as we work with thread, this exception can occur         */        public synchronized void waitUntilDone() throws InterruptedException {            while (!done)                wait();        }    }}
声音文件message.wav放在src的目录下即可,直接运行就可以播放声音了。生命不息,代码不止,有什么不足的地方,希望大家指出。
1 0
原创粉丝点击