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();
Related
".getAudioInputStream(file)" give the error "cannot resolve symbol" (IDE Intellij, java 8)
I try the solution in File > Invalidate Chaces / Restart ... but it doesn't work
package com.Main;
import javax.sound.sampled.Clip;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class SoundEffect {
private String filepath;
private Clip clip;
public SoundEffect(String filepath) {
this.filepath = filepath;
try {
File file = new File(filepath);
AudioInputStream sound = new AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(sound);
}
catch (Exception e) { e.printStackTrace(); }
}
public void play() {
clip.start();
}
}
AudioInputStream sound = new AudioSystem.getAudioInputStream(file);
You don't want to create an instance of an object. You want to invoke a static method of a class.
You don't need the "new".
The code should be:
//AudioInputStream sound = new AudioSystem.getAudioInputStream(file);
AudioInputStream sound = AudioSystem.getAudioInputStream(file);
I tried to make a runnable JAR, but for some reason I couldn't get my game to play. I did some research and ran it through my command prompt to try to find the error and I got this below. So obviously I know the issue I just need to fix it. I have the audio file in my res folder which is in my src. So if it is already in the program I can't figure out why I would get this error. Thoughts?
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Unknown Source)
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at builder.AudioPlayer.playMenuSound(AudioPlayer.java:20)
at builder.Game.<init>(Game.java:56)
at builder.Game.main(Game.java:61)
package builder;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayer {
private static Clip play;
public static void playMenuSound()
{
try {
//AudioInputStream menuSound = AudioSystem.getAudioInputStream(new File("src/res/introSong.wav")); //Take in audio from res folder
AudioInputStream menuSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResourceAsStream("introSong.wav"));
play = AudioSystem.getClip(); //
play.open(menuSound); //Play the sound
FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN); //Get control of volume
volume.setValue(1.0f); //0.0 - 1.0 volume
play.loop(Clip.LOOP_CONTINUOUSLY); //Loop once clip is over
}catch (LineUnavailableException | IOException | UnsupportedAudioFileException e){
e.printStackTrace();
}
}
public static void playGameSound()
{
try {
//AudioInputStream gameSound = AudioSystem.getAudioInputStream(new File("src/res/inGame.wav")); //Take in audio from res folder
AudioInputStream gameSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResourceAsStream("inGame.wav"));
play = AudioSystem.getClip(); //
play.open(gameSound); //Play the sound
FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN); //Get control of volume
volume.setValue(0.5f); //0.0 - 1.0 volume
play.loop(Clip.LOOP_CONTINUOUSLY); //Loop once clip is over
}catch (LineUnavailableException | IOException | UnsupportedAudioFileException e){
e.printStackTrace();
}
}
public static void stopMusic()
{
play.close(); //Stop music
}
}
The problem in your code is where you're trying to instantiate your file with a new reference, here:
AudioInputStream gameSound = AudioSystem.getAudioInputStream(new File("src/res/inGame.wav"));
Instead of doing that, you need to get your file as a resource using a ClassLoader, since it is located inside the resource (res) folder.
Here is how your code should look like:
AudioInputStream gameSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResourceAsStream("inGame.wav"));
Same should be done in with your introSong.wav in the playMenuSound() method. The code should look something like
AudioInputStream gameSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResourceAsStream("introSong.wav"));
I really hope this solves your problem.
I have had success with the following form for setting up Clips. Perhaps it will work for you.
URL url = this.getClass().getResource("audio/" + filename);
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(ais);
The method getResource returns a URL. The method getResourceAsStream returns an InputStream. A URL works as a way to address a file within a jar.
In this example, the file in which the code resides is a parent to the folder "/audio" and the audio resource is in the "/audio" folder.
The following form works for me if you desire to call the loader as a static method.
URL url = AudioPlayer.class.getResource("audio/" + filename);
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();
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.
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.