Clip不会在Java中播放声音

时间:2014-04-30 01:30:50

标签: java url audio

以下代码既不产生声音也不打印堆栈跟踪。如果我调试,踩过clip.start()将会在短时间内播放声音。有没有人知道我做错了什么?感谢。

import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;

public class Driver {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://api.voicerss.org/?KEY=b1a362bc35014e9c9dcd8d3536aac7ad&SRC=This%20is%20a%20test&HL=en-gb&C=WAV&F=48khz_16bit_stereo");
            AudioInputStream sound = AudioSystem.getAudioInputStream(url);
            DataLine.Info info = new DataLine.Info (Clip.class, sound.getFormat());
            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(sound);
            clip.start();
            while(clip.isRunning());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

此外,将while(clip.isRunning(());更改为while(clip.isRunning()) System.out.println("running");不会产生任何输出。

1 个答案:

答案 0 :(得分:0)

关于线程问题.. 当我试图在Event Dispatch Thread中运行它时,运行正常..
你可以从这个讨论中了解EDT:

  

Why do I need Swing Utilities and how do I use it?

注意:我希望其他人可能会找到更好的解决方案..

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.SwingUtilities;

public class Driver {

    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        try {
            URL url = new URL("http://api.voicerss.org/?KEY=b1a362bc35014e9c9dcd8d3536aac7ad&SRC=Your%20a%20fag&HL=en-gb&C=WAV&F=48khz_16bit_stereo");
            AudioInputStream sound = AudioSystem.getAudioInputStream(url);
            DataLine.Info info = new DataLine.Info (Clip.class, sound.getFormat());
            final Clip clip = (Clip)AudioSystem.getLine(info);
            clip.open(sound);
            clip.setFramePosition(0);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    clip.start();
                }
            });

        } catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
            e.printStackTrace();
        }
    }

}