简体   繁体   中英

Clip won't play sound in Java

The following code is neither producing sound nor printing a stack trace. If I debug, stepping over clip.start() will make sound play for a brief fraction of a second. Does anyone have an idea of what I'm doing wrong? Thanks.

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();
        }
    }

}

Also, changing while(clip.isRunning(()); to while(clip.isRunning()) System.out.println("running"); does not result in any output.

It's about thread issue.. when I tried to run it in Event Dispatch Thread, it runs fine..
you may learn about EDT from this discussion:

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

note: I hope others might found better solution for this though..

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();
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM