javando
javando

Reputation: 139

Get sound from a URL with Java

I'm learning english and I'd like to develop a software to help me with the pronunciation.

There is a site called HowJSay, if you enter here: http://www.howjsay.com/index.php?word=car immediatly you'll hear the pronunciation of the word car . I'd like to develop a software in JAVA that could play this sound without necessity of enter in the site =]

I tried this, but doesn't work =/

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.howjsay.com/index.php?word=car");
    url.openConnection();
    AudioStream as = new AudioStream(url.openStream());
    AudioPlayer.player.start(as);
    AudioPlayer.player.stop(as);
}

Any Ideas? Please.

Upvotes: 1

Views: 20051

Answers (4)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Java Sound can play short clips easily, but supports a limited number of formats out of the box. The formats it supports by default are given by AudioSystem.getAudioFileTypes() & that list will not include MP3.

The solution to the lack of support for MP3 is to add a decoder to the run-time class-path of the app. Since Java Sound works on a Service Provider Interface, it only needs to be on the class-path to be useful. An MP3 decoder can be found in mp3plugin.jar.

As to the code for playing the MP3, the short source on the info. page should suffice so long as the clips are short. Viz.

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class LoopSound {

    public static void main(String[] args) throws Exception {
        URL url = new URL(
            "http://pscode.org/media/leftright.wav");
        Clip clip = AudioSystem.getClip();
        // getAudioInputStream() also accepts a File or InputStream
        AudioInputStream ais = AudioSystem.
            getAudioInputStream( url );
        clip.open(ais);
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // A GUI element to prevent the Clip's daemon Thread
                // from terminating at the end of the main()
                JOptionPane.showMessageDialog(null, "Close to exit!");
            }
        });
    }
}

Upvotes: 2

Xaethriux
Xaethriux

Reputation: 1

If you're having issues with the code provided by Marek, make sure you're meeting this criteria:

  1. Use a supported audio format, such as 16 bit .wav
  2. Make sure that the URL you're using is actually playing audio automatically.

It isn't sufficient to simply reference the download page for an audio file. It has to be streaming the audio. YouTube URLs won't work, as they're videos. Audacity is a good approach to converting your audio file to a compatible 16 bit .wav file, and if you have your own domain / website, you can provide a direct link to the file from there.

Upvotes: 0

Marek
Marek

Reputation: 1878

Here you go

import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;

public class HowJSay
{
public static void main(String[] args) {
    AudioInputStream din = null;
    try {
        AudioInputStream in = AudioSystem.getAudioInputStream(new URL("http://www.howjsay.com/mp3/"+ args[0] +".mp3"));
        AudioFormat baseFormat = in.getFormat();
        AudioFormat decodedFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                false);
        din = AudioSystem.getAudioInputStream(decodedFormat, in);
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
        SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
        if(line != null) {
            line.open(decodedFormat);
            byte[] data = new byte[4096];
            // Start
            line.start();

            int nBytesRead;
            while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
                line.write(data, 0, nBytesRead);
            }
            // Stop
            line.drain();
            line.stop();
            line.close();
            din.close();
        }

    }
    catch(Exception e) {
        e.printStackTrace();
    }
    finally {
        if(din != null) {
            try { din.close(); } catch(IOException e) { }
        }
    }
}

}

Upvotes: 4

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

If you don't care much about the site then you try to use Google Translate API

try{
        String word="car";
        word=java.net.URLEncoder.encode(word, "UTF-8");
        URL url = new URL("http://translate.google.com/translate_tts?ie=UTF-8&tl=ja&q="+word);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.addRequestProperty("User-Agent", "Mozilla/4.76");
        InputStream audioSrc = urlConn.getInputStream();
        DataInputStream read = new DataInputStream(audioSrc);
        AudioStream as = new AudioStream(read);
        AudioPlayer.player.start(as);
        AudioPlayer.player.stop(as);
}

With help from here: Java: download Text to Speech from Google Translate

If for every word the site guarantees to have mp3 file with link howjsay.com/mp3/word.mp3 then you just need to change URL to

URL url = new URL("howjsay.com/mp3/" + word + ".mp3");

Upvotes: 1

Related Questions