Get sound from a URL with Java - 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.

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) { }
}
}
}
}

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!");
}
});
}
}

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");

If you're having issues with the code provided by Marek, make sure you're meeting this criteria:
Use a supported audio format, such as 16 bit .wav
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.

Related

Play sound in GUI program

I have been experimenting with Java Swing using a GUI and have hit a wall. I am trying to play a sound using Java Sound. Ultimately, I want to push a button and the sound plays. I have tried a lot of combinations but none seem to work. Here is the latest code I tried and I code and it reports:
Error: could not find or load main class.
I am not seeing why:
package net.codejava.sound;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* This is an example program that demonstrates how to play back an audio file
* using the SourceDataLine in Java Sound API.
* #author www.codejava.net
*
*/
public class AudioPlayerExample2 {
// size of the byte buffer used to read/write the audio stream
private static final int BUFFER_SIZE = 4096;
/**
* Play a given audio file.
* #param audioFilePath Path of the audio file.
*/
void play(String audioFilePath) {
File audioFile = new File(audioFilePath);
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine audioLine = (SourceDataLine) AudioSystem.getLine(info);
audioLine.open(format);
audioLine.start();
System.out.println("Playback started.");
byte[] bytesBuffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = audioStream.read(bytesBuffer)) != -1) {
audioLine.write(bytesBuffer, 0, bytesRead);
}
audioLine.drain();
audioLine.close();
audioStream.close();
System.out.println("Playback completed.");
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
public static void main(String[] args) {
String audioFilePath = "https://codehs.com/uploads/1981fc4b1d2e4123e9cbe7ab8cc1962a";
AudioPlayerExample2 player = new AudioPlayerExample2();
player.play(audioFilePath);
}
}
I made a couple small changes to the tutorial code example you posted, and the program worked perfectly well.
Here are my changes:
(1) Replaced "File audioFile = new File(audioFilePath);" with the following:
URL audioFile = null;
try {
audioFile = new URL(audioFilePath);
} catch (MalformedURLException e) {
e.printStackTrace();
}
(2) Added the following line to the module-info file (required if you are using Java 9 or higher):
requires java.desktop;
My package setting is slightly different, but I assume you know how to properly set up packages. Your class is in the file folder specified by the package statement, yes?
The error being cited: "could not find or load main class" indicates that something is going wrong with how the code is being invoked rather than a problem with the audio part of the code. What version of Java are you using? What IDE? What is the command you are issuing to execute the program? FWIW, my setup that successfully executed this code has an up-to-date Eclipse IDE running Java 11.
Nam Ha Minh's tutorials at codejava.net usually are quite good. I think he is one of the more reliable tutorial writers out there.

javax.sound.sampled.UnsupportedAudioFileException playing OGG files with javazoom

I'm attempting to play OGG audio files using an answer to another question here: Playing ogg files in eclipse
Using the javazoom library which I successfully downloaded and configured for my project, I am attempting to use the xav's answer code:
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javazoom.spi.PropertiesContainer;
public class OGGPlayer {
public final String fileName;
public boolean mustStop = false;
public OGGPlayer(String pFileName) {
fileName = pFileName;
}
public void play() throws Exception {
mustStop = false;
File file = new File(fileName);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
if (audioInputStream == null) {
throw new Exception("Unable to get audio input stream");
}
AudioFormat baseFormat = audioInputStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
AudioInputStream decodedAudioInputStream = AudioSystem.getAudioInputStream(decodedFormat,
audioInputStream);
if (!(decodedAudioInputStream instanceof PropertiesContainer)) {
throw new Exception("Wrong PropertiesContainer instance");
}
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, decodedFormat);
SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(decodedFormat);
byte[] tempBuffer = new byte[4096];
// Start
sourceDataLine.start();
int nbReadBytes = 0;
while (nbReadBytes != -1) {
if (mustStop) {
break;
}
nbReadBytes = decodedAudioInputStream.read(tempBuffer, 0, tempBuffer.length);
if (nbReadBytes != -1)
sourceDataLine.write(tempBuffer, 0, nbReadBytes);
}
// Stop
sourceDataLine.drain();
sourceDataLine.stop();
sourceDataLine.close();
decodedAudioInputStream.close();
audioInputStream.close();
}
public void setMustStop(boolean pMustStop) {
mustStop = pMustStop;
}
public void stop() {
mustStop = true;
}
}
The code makes sense to me, but I am having trouble simply using it. I can't seem to get the class to read my OGG file, and I've modified it various ways in attempts to make this function. I read WAV files in this same project, reading the files completely successfully with
AudioInputStream audioIn = AudioSystem.getAudioInputStream(Thread.currentThread().getContextClassLoader().getResource("res/audio/" + fileName + ".wav"));
I've attempted variations of this, using the File class, reading as a resources, and I can successfully locate my OGG file in the project, but it keep throwing the exception
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL
This is my fourth or fifth attempt in getting audio to play non-WAV audio in this project. I tried playing MP3s with MediaPlayer and a few other ways, and this is my second method method of trying to play OGG files. I'm trying to play large, long music tracks as background, and I cannot run them as I do my other WAV sound effects due to file size.
Any help in playing these OGG files would be immensely appreciated. I feel so close to my goal with this attempt, it seems simple and solid, but it just refuses to read my files correctly. Thank you in advance for any assistance.
Here's a method that will read mp3 and ogg files - it will play files with the vorbis format but not flac; so you have to put a check there - not all files ending with .ogg will be supported:
import javazoom.spi.vorbis.sampled.file.VorbisAudioFileReader;
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;
import org.tritonus.share.sampled.file.TAudioFileReader;
import org.tritonus.sampled.file.AuAudioFileReader;
AudioInputStream createOggMp3(File fileIn) throws IOException, Exception {
AudioInputStream audioInputStream=null;
AudioFormat targetFormat=null;
try {
AudioInputStream in=null;
if(fileIn.getName().endsWith(".ogg")) {
VorbisAudioFileReader vb=new VorbisAudioFileReader();
in=vb.getAudioInputStream(fileIn);
}
else if(fileIn.getName().endsWith(".mp3")) {
MpegAudioFileReader mp=new MpegAudioFileReader();
in=mp.getAudioInputStream(fileIn);
}
AudioFormat baseFormat=in.getFormat();
targetFormat=new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
audioInputStream=AudioSystem.getAudioInputStream(targetFormat, in);
}
catch(UnsupportedAudioFileException ue) { System.out.println("\nUnsupported Audio"); }
return audioInputStream;
}
It returns you an audio input stream which you can use as follows:
if(fileIn.getName().endsWith(".ogg") || fileIn.getName().endsWith(".mp3")) {
audioInputStream=createOggMp3(fileIn);
}
else { // wav
audioInputStream=AudioSystem.getAudioInputStream(fileIn);
}
Your decoded audio format is
decodedFormat=audioInputStream.getFormat();
and then you can continue with your SourceDataline.

How can I read local .wav file into sound and play it in java [duplicate]

package soundTest;
import java.applet.*;
import java.net.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.io.*;
import java.util.*;
public class SoundTest {
public static void main(String[] args) throws Exception {
try {
AudioClip clip1 = Applet.newAudioClip(new URL(new File("E0.wav").getAbsolutePath()));
clip1.play();
} catch (MalformedURLException murle) {
System.out.println(murle);
}
URL url = new URL(
"http://www.mediafire.com/listen/tok9j9s1hnogj1y/downloads/E0.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
URL url2 = new URL(
"http://www.villagegeek.com/downloads/webwavs/Austin_Powers_death.wav");
Clip clip2 = AudioSystem.getClip();
AudioInputStream ais2 = AudioSystem.
getAudioInputStream(url2);
clip2.open(ais2);
clip.loop(1);
clip2.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
I can't figure out how to play a wav file from my computer (not from a URL) in java. I'm sure that I have it placed in the right area, the SRC (I also placed it in practically every other space just in case...).
The first attempt is from http://www.cs.cmu.edu/~illah/CLASSDOCS/javasound.pdf
It gives the me the catch statement.
The second attempt was putting my recorded .wav file on mediafire. However, that didn't work. "Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL"
The third example works fine, but, unlike my file, it's a file from online. When you click on that one, it brings you to just an audio player, while the mediafire link brings you to a page with other stuff and some application that plays the file.
First Attempt
AudioClip clip1 = Applet.newAudioClip(new URL(new File("E0.wav").getAbsolutePath()));
This is not how you construct a URL to a File. Instead, you should use File#getURI#getURL
AudioClip clip1 = Applet.newAudioClip(new File("/full/path/to/audio.wav").toURI().toURL());
Second Attempt
mediafire is returning a html response, not the audio file...You can test it with...
URL url = new URL("http://www.mediafire.com/listen/tok9j9s1hnogj1y/downloads/E0.wav");
try (InputStream is = url.openStream()) {
int in = -1;
while ((in = is.read()) != -1) {
System.out.print((char)in);
}
} catch (IOException exp) {
exp.printStackTrace();
}
Third Attempt
You open the clip, but never start it...
URL url2 = new URL("http://www.villagegeek.com/downloads/webwavs/Austin_Powers_death.wav");
Clip clip2 = AudioSystem.getClip();
AudioInputStream ais2 = AudioSystem.getAudioInputStream(url2);
clip2.open(ais2);
clip2.start();

Playing .wav file in java from file from computer

package soundTest;
import java.applet.*;
import java.net.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.io.*;
import java.util.*;
public class SoundTest {
public static void main(String[] args) throws Exception {
try {
AudioClip clip1 = Applet.newAudioClip(new URL(new File("E0.wav").getAbsolutePath()));
clip1.play();
} catch (MalformedURLException murle) {
System.out.println(murle);
}
URL url = new URL(
"http://www.mediafire.com/listen/tok9j9s1hnogj1y/downloads/E0.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
URL url2 = new URL(
"http://www.villagegeek.com/downloads/webwavs/Austin_Powers_death.wav");
Clip clip2 = AudioSystem.getClip();
AudioInputStream ais2 = AudioSystem.
getAudioInputStream(url2);
clip2.open(ais2);
clip.loop(1);
clip2.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
I can't figure out how to play a wav file from my computer (not from a URL) in java. I'm sure that I have it placed in the right area, the SRC (I also placed it in practically every other space just in case...).
The first attempt is from http://www.cs.cmu.edu/~illah/CLASSDOCS/javasound.pdf
It gives the me the catch statement.
The second attempt was putting my recorded .wav file on mediafire. However, that didn't work. "Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL"
The third example works fine, but, unlike my file, it's a file from online. When you click on that one, it brings you to just an audio player, while the mediafire link brings you to a page with other stuff and some application that plays the file.
First Attempt
AudioClip clip1 = Applet.newAudioClip(new URL(new File("E0.wav").getAbsolutePath()));
This is not how you construct a URL to a File. Instead, you should use File#getURI#getURL
AudioClip clip1 = Applet.newAudioClip(new File("/full/path/to/audio.wav").toURI().toURL());
Second Attempt
mediafire is returning a html response, not the audio file...You can test it with...
URL url = new URL("http://www.mediafire.com/listen/tok9j9s1hnogj1y/downloads/E0.wav");
try (InputStream is = url.openStream()) {
int in = -1;
while ((in = is.read()) != -1) {
System.out.print((char)in);
}
} catch (IOException exp) {
exp.printStackTrace();
}
Third Attempt
You open the clip, but never start it...
URL url2 = new URL("http://www.villagegeek.com/downloads/webwavs/Austin_Powers_death.wav");
Clip clip2 = AudioSystem.getClip();
AudioInputStream ais2 = AudioSystem.getAudioInputStream(url2);
clip2.open(ais2);
clip2.start();

Playing sound in a Java Desktop application

How do we play sound (a music file of any format like .wma, .mp3 ) in a Java desktop application? (not an applet)
I have used the following code (taken from another question on Stack Overflow) but it throws an Exception.
public class playsound {
public static void main(String[] args) {
s s=new s();
s.start();
}
}
class s extends Thread{
public void run(){
try{
InputStream in = new FileInputStream("C:\\Users\\srgf\\Desktop\\s.wma");
AudioStream as = new AudioStream(in); //line 26
AudioPlayer.player.start(as);
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
The program when run throws the following Exception:
java.io.IOException: could not create audio stream from input stream
at sun.audio.AudioStream.<init>(AudioStream.java:82)
at s.run(delplaysound.java:26)
Use this library:
http://www.javazoom.net/javalayer/javalayer.html
public void play() {
String song = "http://www.ntonyx.com/mp3files/Morning_Flower.mp3";
Player mp3player = null;
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new URL(song).openStream());
mp3player = new Player(in);
mp3player.play();
} catch (MalformedURLException ex) {
} catch (IOException e) {
} catch (JavaLayerException e) {
} catch (NullPointerException ex) {
}
}
Hope that helps everyone with a similar question :-)
Hmmm. This might look like advertisement for my stuff, but you could use my API here:
https://github.com/s4ke/HotSound
playback is quite easy with this one.
Alternative: use Java Clips (prebuffering)
... code ...
// specify the sound to play
File soundFile = new File("pathToYouFile");
//this does the conversion stuff for you if you have the correct SPIs installed
AudioInputStream inputStream =
getSupportedAudioInputStreamFromInputStream(new FileInputStream(soundFile));
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
// due to bug in Java Sound, explicitly exit the VM when
// the sound has stopped.
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
System.exit(0);
}
}
});
// play the sound clip
clip.start();
... code ...
Then you need this method:
public static AudioInputStream getSupportedAudioInputStreamFromInputStream(InputStream pInputStream) throws UnsupportedAudioFileException,
IOException {
AudioInputStream sourceAudioInputStream = AudioSystem
.getAudioInputStream(pInputStream);
AudioInputStream ret = sourceAudioInputStream;
AudioFormat sourceAudioFormat = sourceAudioInputStream.getFormat();
DataLine.Info supportInfo = new DataLine.Info(SourceDataLine.class,
sourceAudioFormat,
AudioSystem.NOT_SPECIFIED);
boolean directSupport = AudioSystem.isLineSupported(supportInfo);
if(!directSupport) {
float sampleRate = sourceAudioFormat.getSampleRate();
int channels = sourceAudioFormat.getChannels();
AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sampleRate,
16,
channels,
channels * 2,
sampleRate,
false);
AudioInputStream convertedAudioInputStream = AudioSystem
.getAudioInputStream(newFormat, sourceAudioInputStream);
sourceAudioFormat = newFormat;
ret = convertedAudioInputStream;
}
return ret;
}
Source for the Clip example (with little changes by me): http://www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm
SPIs are added via adding their .jars to the classpath
for mp3 these are:
http://www.javazoom.net/mp3spi/mp3spi.html
http://www.javazoom.net/javalayer/javalayer.html
http://www.tritonus.org/plugins.html (tritonus_share.jar)
Using JavaFX (which is bundled with your JDK) is pretty simple.
You will need the following imports:
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;
import java.nio.file.Paths;
Steps:
Initialize JavaFX:
new JFXPanel();
Create a Media (sound):
Media media = new Media(Paths.get(filename).toUri().toString());
Create a MediaPlayer to play the sound:
MediaPlayer player = new MediaPlayer(media);
And play the Media:
player.play();
You can set the start/stop times as well with MediaPlayer.setStartTime() and MediaPlayer.setStopTime():
player.setStartTime(new Duration(Duration.ZERO)); // Start at the beginning of the sound file
player.setStopTime(1000); // Stop one second (1000 milliseconds) into the playback
Or, you can stop playing with MediaPlayer.stop().
A sample function to play audio:
public static void playAudio(String name, double startMillis, double stopMillis) {
Media media = new Media(Paths.get(name).toUri().toString());
MediaPlayer player = new MediaPlayer(media);
player.setStartTime(new Duration(startMillis));
player.setStopTime(new Duration(stopMillis));
player.play();
}
More info can be found at the JavaFX javadoc.

Categories