0

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.

asantas93
  • 31
  • 3

1 Answers1

0

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

}
Community
  • 1
  • 1
  • This exact code doesn't produce sound on my computer. I'm using Eclipse on Ubuntu with open jdk (I also tried running it from terminal). Would that somehow be an issue? – asantas93 Apr 30 '14 at 02:33