This question already has answers here:
Playing .mp3 and .wav in Java?
(15 answers)
Closed 8 years ago.
I want to play an audio file when certain conditions are met but I can't figure it out. I am inexperienced in java and programming in general and copied several blocks of code and none of them work.
Trying to play this:
File type: .mp3
Location: C:\Users\Public\Music\Sample Music
I wasted close to two hours on this. Plz help with code that just plays audio from a file. Thank you.
Update: I keep getting this error
Multiple markers at this line
- Access restriction: The type AudioStream is not accessible due to restriction on required library C:\Program Files (x86)\Java\jre1.8.0_25\lib\rt.jar
- Access restriction: The type AudioStream is not accessible due to restriction on required library C:\Program Files (x86)\Java\jre1.8.0_25\lib\rt.jar
- Access restriction: The constructor AudioStream(InputStream) is not accessible due to restriction on required library C:\Program Files (x86)\Java
Check Xuggle or jLayer.
Google them and you will come up with nice results.
Good >> http://kxhitiz.blogspot.com.tr/2010/09/playing-mp3-in-java-programming.html
Java Jlayer Mp3 Player - how to repeat and stop song
public class JavaAudioPlaySoundExample
{
public static void main(String[] args)
throws Exception
{
// open the sound file as a Java input stream
String gongFile = "/Users/al/DevDaily/Projects/MeditationApp/resources/gong.au";
InputStream in = new FileInputStream(gongFile);
// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
}
}
Related
I want to play .mp3 files in Vaadin 14. This is my audio player.
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
#Tag("audio")
public class AudioPlayer extends Component {
/**
*
*/
private static final long serialVersionUID = 1L;
public AudioPlayer(){
getElement().setAttribute("controls",true);
}
public void setSource(String path){
getElement().setProperty("src",path);
}
}
AudioPlayer player = new AudioPlayer();
player.setSource("music/my music file.mp3");
add(player);
But when I try to play .mp3 files, nothing happens. What have I missed?
Do I need to convert .mp3 files to .wav before? How can I do that just temporary.
I'm not planning to save any .wav files on the computer, because I already have .mp3 files stored.
Your approach should work, I just create a PR to the Vaadin cookbook with a recipe for this.
Note that the browser needs to be able to access the audio file through that same path. If you set the src to audio/mysong.mp3, then you should be able to open it in the browser also as e.g. localhost:8080/audio/mysong.mp3 (or the equivalent URL for your setup).
Take a look at the ways of importing in Vaadin to see where to put your file, in particular the Resource Cheat Sheet for static files.
Edit:
I'm not sure why your files don't work on the first try, but I could reproduce it in your project, also with my own mp3 files. You can see an error 416 in the console, something to do with a mismatch in the range of bytes requested.
I found a workaround that you could try (you might want to move your audio to just src/main/resources for this, and/or update the AudioPlayer to accept an AbstractStreamResource):
if(!reverseTranslation.getValue()) {
frenchSentence.setValue(sentenceInFrench);
String audioPath = "/META-INF/resources/audio/" + sentenceInFrench + ".mp3";
AbstractStreamResource resource =
new StreamResource(sentenceInFrench, () -> getClass().getResourceAsStream(audioPath));
player.getElement().setAttribute("src", resource);
}
The message on the shell is:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
at reprod.ReproducirFichero(reprod.java:16)
at reprod.main(reprod.java:44)
I try to download new drivers for audio, i try to reinstall openJDK 7 and openJRE 7 and also i try to install java 7.
I have proved my code in another computer and it works, the desktop board that i use is an intel d525mw, the audio format that i´m trying to play is .wav.The version of linux that I use is Ubuntu 12.04.3.Please I need help.Thanks
here is party of my code, and i try to play a .wav audio format
import javax.sound.sampled.*;
public class reprod {
public static void play(){
try {
Clip cl = AudioSystem.getClip();
File f = new File("/home/usr/Desktop/d.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(f);
cl.open(ais);
cl.start();
System.out.println("playing...");
while (cl.isRunning())
Thread.sleep(4000);
cl.close();
the version of linux that I use is Ubuntu 12.04.3
I solved the problem by simply passing the parameter null into AudioSystem.getClip().
I don't know why this exception occured, I run this project before on Windows, and it worked... After on Linux and here, it didn't work.
I had the same problem and found this code to work:
File soundFile = new File("/home/usr/Desktop/d.wav");
AudioInputStream soundIn = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = soundIn.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(soundIn);
clip.start();
while(clip.isRunning())
{
Thread.yield();
}
The key is in soundIn.getFormat(). To quote the docs:
Obtains the audio format of the sound data in this audio input stream.
Source: http://ubuntuforums.org/showthread.php?t=1469572
The error message says that the input file format is wrong somehow.
If you gave us more information (file format, maybe where you got it, code that you use to open the file and how you configured the audio drivers), we might be able to help.
See this question for some code that you can try: How to play .wav files with java
This is my code
public static void main(String[] args) {
try{
// open the sound file as a Java input stream
InputStream in = new FileInputStream("Sound.wav");
// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
}
catch(Exception e){
System.out.println("Audio not found");
}
}
Sun Audio is Undocumented
You should not be using Sun Audio in your program. See here and here.
The Answer Depends on Your Library
If you are using Java Clip (built-in), try the example here. This is probably the simplest method.
If you switch to use JavaFX, you can see the API here, which has ways to loop. However, JavaFX requires a bit of package restructuring, and there is a learning curve. Unless you need JavaFX for other reasons, I would avoid it.
If you are using any other library, please consult the API for that library, or share with us what you are attempting to use. I have personally used BasicPlayer, but it is quite old.
I am trying to program a classroom assistant (I work as a teacher) using Java who will give spoken instructions to students/ask them questions etc. I have managed to connect successfully to the cerevoice cloud to create an ogg file
e.g. "https://cerevoice.s3.amazonaws.com/Heather220501c8c2e94d4650f64f7d951bf76b08b0eb.ogg"
however when I try to play this ogg file from java I get an error that it could not be found or that it is an unsupported audio resource depending on the ogg player I use (i have tried EasyOGG and TinySound so far) - both the ogg players work successfully locally but I cannot get them to play a file directly from the website.
Examples how I have tried to reference it:
URL url = new URL("https://cerevoice.s3.amazonaws.com/Heather220501c8c2e94d4650f64f7d951bf76b08b0eb.ogg");
Music song = TinySound.loadMusic(url);
song.play(true);
OggClip ogg = new OggClip("https://cerevoice.s3.amazonaws.com/Heather220501c8c2e94d4650f64f7d951bf76b08b0eb.ogg");
ogg.loop();
Apologies for my ignorance I'd really appreciate any help anyone can give with playing this file! =)
Many thanks,
Darren
Edited to show using a literal String value to help clarity
Edit very ugly hack 1 solution: //opens a browser window plays file then closes window
String url = "https://cerevoice.s3.amazonaws.com/Heather220501c8c2e94d4650f64f7d951bf76b08b0eb.ogg"; //hard coded here for simplicity but URL dynamically retrieved from webservice
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
Thread.sleep(3000);
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
Edit slightly less ugly hack 2 solution:
//creation of a temporary file to allow playing from java without creating a browser window
try{
Files.deleteIfExists(Paths.get("C:/cere/temp.ogg"));
try (InputStream in = URI.create(url.value).toURL().openStream()) {
Files.copy(in, Paths.get("C:/cere/temp.ogg"));
}catch(IOException e) {
}
i am trying to loop an audio file but when i've tried the other various methods available, my music doesn't play.
My basic code is:
import java.io.*;
import sun.audio.*;
public class PlayMusic {
public void playSound() {
try {
AudioPlayer p = AudioPlayer.player;
AudioStream as = new AudioStream(new FileInputStream("02 River Flows In You.wav"));
p.start(as);
} catch (IOException IOE) {
}
}
I've never seen sun.audio.AudioPlayer in use before! I've always used the javax.sound.sampled library.
Maybe you can tell me how you came across it. It looks to me like rather old code (10 years?) and also a bit on the limited side.
I think, if you aren't getting a single playback, you should try the URL form:
AudioStream audiostream = new AudioStream(url.openStream());
AudioPlayer.player.start(audiostream);
Then try putting the code in a loop? A lot depends on whether the .start command blocks or not. If it launches a separate thread (most likely), then you will have to figure out when the file ends, and I don't see any commands provided to do that! The spec also lists the possibility of creating an ContinuousAudioDataStream and managing that.
Unless there is something I don't know about this library that I should, I recommend using either a javax.sound.sampled.Clip, or javax.sound.sampled.SourceDataLine for playback. The Clip has a boolean you can set for looping, but requires the entire file be loaded into memory first. The SourceDataLine plays back from a url or file location, and can implement a listener to tell you when the file is done.
http://docs.oracle.com/javase/tutorial/sound/playing.html