Java-播放WAV音频

来源:互联网 发布:上海软件培训机构 编辑:程序博客网 时间:2024/04/29 06:23
public class Test {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        AePlayWave apw=new AePlayWave("aaa.wav");        apw.start();    }}class AePlayWave extends Thread {    private String filename;    public AePlayWave(String wavfile) {        filename = wavfile;    }    public void run() {        File soundFile = new File(filename);        // 获取音频输入流        AudioInputStream audioInputStream = null;        try {            audioInputStream = AudioSystem.getAudioInputStream(soundFile);        } catch (Exception e1) {            e1.printStackTrace();            return;        }        // 获取音频编码对象        AudioFormat format = audioInputStream.getFormat();        // 设置数据输入        SourceDataLine auline = null;        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);        try {            auline = (SourceDataLine) AudioSystem.getLine(info);            auline.open(format);        } catch (Exception e) {            e.printStackTrace();            return;        }        auline.start();      /*       * 从输入流中读取数据发送到混音器       */        int nBytesRead = 0;        byte[] abData = new byte[512];        try {            while (nBytesRead != -1) {                nBytesRead = audioInputStream.read(abData, 0, abData.length);                if (nBytesRead >= 0)                    auline.write(abData, 0, nBytesRead);            }        } catch (IOException e) {            e.printStackTrace();            return;        } finally {            // 清空数据缓冲,并关闭输入            auline.drain();            auline.close();        }    }}
0 0