在Daemon-Thread中播放WAV文件

时间:2015-10-26 10:25:56

标签: java multithreading audio

如何在守护程序线程中的无限循环中播放WAV文件?我测试过的任何东西都没用。程序总是在没有做任何事情的情况下退出。

public class BackgroundSoundThread extends Thread {
    private final URL url;
    private final AudioInputStream audioStream;
    private final AudioFormat audioFormat;
    private final  SourceDataLine sourceLine;

    public BackgroundSoundThread(URL url) throws IOException, LineUnavailableException, UnsupportedAudioFileException {
        this.setDaemon(true);    
        this.url = url;

        audioStream = AudioSystem.getAudioInputStream(getClass().getResource("resources/launcher.wav"));
        audioFormat = audioStream.getFormat();
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        sourceLine = (SourceDataLine) AudioSystem.getLine(info);
    }

    @Override public void run() {
        try {
            sourceLine.open(audioFormat);
            sourceLine.start();

            int size = (int)(audioFormat.getFrameSize() * audioStream.getFrameLength());
            byte[] data = new byte[size];
            audioStream.read(data, 0, size);
            sourceLine.write(data, 0, size);

            sourceLine.drain();
            sourceLine.close();
        } catch (Exception e) {
            // here is exception handling
        }
    }

    public void pause(boolean b) {
        // what here??
    }
}

0 个答案:

没有答案