so I've been working on my game library and I just got working on the sound aspect of it. But the problems are that the Sound starts playing from the constructor instead of the play method and also the stop doesn't work for the constructor and only the play method.
I tried debugging the code but I didn't get any results from it. I also tried using the stop method before doing the play method but that didn't work either
below is the code,
import java.io.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
// class stuff
private Clip clip;
private FloatControl fc;
public SoundLoader(File file) {
try {
InputStream audioSource = new FileInputStream(file);
InputStream bufferedInput = new BufferedInputStream(audioSource);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bufferedInput);
AudioFormat baseFormat = audioInputStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
baseFormat.getSampleSizeInBits(),
baseFormat.getChannels(),
baseFormat.getFrameSize(),
baseFormat.getFrameRate(),
false
);
AudioInputStream decodedAudioInputStream = AudioSystem.getAudioInputStream(decodedFormat, audioInputStream);
clip = AudioSystem.getClip();
clip.open(decodedAudioInputStream);
fc = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void play(boolean loop){
if(clip == null || isRunning())return;
stop();
while(!clip.isRunning())
clip.start();
if(loop)clip.loop(Clip.LOOP_CONTINUOUSLY);
}
and here is an example of what's happening in log form,
clip starts running from constructor
same clip starts running from play method
stop method stops the clip from running from the play method
constructor keeps on playing
If anyone knows why this is happening it would be nice if you could reply to this. Thanks
edit: I changed clip and fc to not static because I use testing something out with static and then I forgot to change it back to normal
okay I solved it. It was just a case of me blacking out while I was coding and I was playing the sound in the main method of the project. I'm glad that it wasn't a problem with the Clip class
Related
How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
But, this will only play .wav files.
The same with:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
I want to be able to play both .mp3 files and .wav files with the same method.
Java FX has Media and MediaPlayer classes which will play mp3 files.
Example code:
String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
You will need the following import statements:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
I wrote a pure java mp3 player: mp3transform.
Using standard javax.sound API, lightweight Maven dependencies, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:
pom.xml:
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
Code:
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.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
References:
http://odoepner.wordpress.com/2013/07/19/play-mp3-using-javax-sound-sampled-api-and-mp3spi/
you can play .wav only with java API:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
code:
AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
And play .mp3 with jLayer
It's been a while since I used it, but JavaLayer is great for MP3 playback
I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX.
http://www.javazoom.net/jlgui/api.html
After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:
basicplayer3.0.jar
all the jars from the lib directory (inside BasicPlayer3.0)
Here is a minimalistic usage example:
String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
player.open(new URL("file:///" + pathToMp3));
player.play();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
Required imports:
import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.
For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html
The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp).
It demonstrates the advanced features of the BasicPlayer pretty well.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
very low CPU usage (~2%)
incredible small library (~90KB)
doesn't need JMF (Java Media Framework)
easy to integrate in any application
easy to integrate in any web page (as applet).
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
UPDATE(2022)
The download link at that page does not work anymore, but there is a sourceforge project
Using MP3 Decoder/player/converter Maven Dependency.
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class PlayAudio{
public static void main(String[] args) throws FileNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream("mp.mp3");
Player player = new Player((fileInputStream));
player.play();
System.out.println("Song is playing");
while(true){
System.out.println(player.getPosition());
}
}catch (Exception e){
System.out.println(e);
}
}
}
You need to install JMF first (download using this link)
File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();
don't forget to add JMF jar files
Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.
You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.
To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.
Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.
I have other methods for that, the first is :
public static void playAudio(String filePath){
try{
InputStream mus = new FileInputStream(new File(filePath));
AudioStream aud = new AudioStream(mus);
}catch(Exception e){
JOptionPane.showMessageDialig(null, "You have an Error");
}
And the second is :
try{
JFXPanel x = JFXPanel();
String u = new File("021.mp3").toURI().toString();
new MediaPlayer(new Media(u)).play();
} catch(Exception e){
JOPtionPane.showMessageDialog(null, e);
}
And if we want to make loop to this audio we use this method.
try{
AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
AudioPlayer.player.start(s);
} catch(Exception ex){
JOPtionPane.showMessageDialog(null, ex);
}
if we want to stop this loop we add this libreries in the try:
AudioPlayer.player.stop(s);
for this third method we add the folowing imports :
import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
Nothing worked. but this one perfectly 👌
google and download Jlayer library first.
import javazoom.jl.player.Player;
import java.io.FileInputStream;
public class MusicPlay {
public static void main(String[] args) {
try{
FileInputStream fs = new FileInputStream("audio_file_path.mp3");
Player player = new Player(fs);
player.play();
} catch (Exception e){
// catch exceptions.
}
}
}
Use this library: import sun.audio.*;
public void Sound(String Path){
try{
InputStream in = new FileInputStream(new File(Path));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e){}
}
After some days of research on the internet, I came here looking for help. I'm currently developing a short 2D game for friends (and really just for fun), and I learned about Clips some days ago. In this game, the player can gather objects (almost like the coins in Mario). My problem is that I have a very short sound (~ 1 sec for 50kB) played when gathering a coin, and if the player gather let's say 3 coins in 1 second, then the Clip make the game lag. If the precedent Clip has ended, then there is no lag. But if the precedent Clip has not ended, then trying to play the Clip again make the game lag (very much).
I have a very small computer, not very powerful, but this problem is really annoying. I get the exact same problem with a sound when the player throws a weapon. I have a short clip, and if the player throws this weapon too fast, the game lag ...
Here is the things I already tried :
Use an array of clips (of this same sound), and play a clip that is not currently playing
Use different clips (of this same sound), and same as before
Make multiple copies (of this same sound), and load it in different clips
Make a separate thread for playing sounds, but I'm not comfortable at all with threads :/
But none of these change this problem ...
Now here is part of my code. First is the class that I use to load a sound into Clip.
package sound;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
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;
// My own package
import utils.Utils;
public class SoundLoader {
public static Clip loadSound(String path) {
Utils.log("Loading " + path + " ... ");
try {
URL url = SoundLoader.class.getResource(path);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
AudioFormat format = audioIn.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(audioIn);
Utils.log("success\n");
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
Utils.log("failed !\n");
return null;
}
}
}
Now is the class where I'll manage all sounds :
package sound;
import javax.sound.sampled.Clip;
// My own package
import principal.Handler;
public class SoundManager {
private Clip woosh;
private Clip coin1;
private Clip coin2;
public SoundManager(Handler handler) {
woosh = SoundLoader.loadSound("/resources/sounds/woosh2.wav");
coin1 = SoundLoader.loadSound("/resources/sounds/coin1.wav");
coin2 = SoundLoader.loadSound("/resources/sounds/coin2.wav");
}
public void wooshClip() {
startClip(woosh);
}
public void coin1Clip() {
startClip(coin1);
}
public void coin2Clip() {
startClip(coin2);
}
public synchronized void startClip(Clip clip) {
clip.stop();
clip.setFramePosition(0);
clip.start();
}
public void loopClip(Clip clip) {
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stopClip(Clip clip) {
clip.stop();
}
}
And finally, when I want to play a Clip, I use the public method startClip() from my "Player" class (representing obviously the player).
handler.getSoundManager().wooshClip();
As I see my code, if the Clip is already playing, then the method starClip() should just stop it and replay it. Why is it lagging so much ? And why is it lagging even if I use different Clips ? What does make my game lag if I'm just stopping a Clip and replay it ?
I hope you will be able to help me ... It's rare that I don't find an answer on the web. If you need anything more to answer me just let me know !
Thanks for your time spent on this long question !
EDIT : I tried my game on a much powerful computer and there is absolutely no lag because of the audio clips ... But my question remains ! How could a 50kB clip make so much lag ?? I really don't understand the problem ...
Solution
I just discovered a solution while working on this project : now my entities that should play a sound when gathered by the player (like the sound of a coin in Mario) contain the audio clip of their "death". I don't understand exactly why it works now but it does ...
Use javafx.scene.media.AudioClip from JavaFX instead of javax.sound.sampled.Clip. AudioClip has lower latency.
I've found some would-be answers on Stack Overflow, but they are old and it looks like they use deprecated technologies.
I need to play an mp3 file given an absolute file name.
Here is what I've tried:
1. JavaFX
MediaPlayer player = new MediaPlayer(new Media(uriString));
I am getting java.lang.IllegalStateException: Toolkit not initialized.
I could probably find a way to initialize that toolkit, but I'd like to know if it's the preferred way.
2. Intellij UIUtil
final InputStream is = new FileInputStream(fileName);
UIUtil.playSoundFromStream(new Factory<InputStream>() {
#Override
public InputStream create() {
return is;
}
});
I am getting Audio format is not yet supported: could not get audio input stream from input file
I've made some more attempts, but this is what I have a record of.
The only thing that's working for me so far is playing files from shell: on Mac,
Runtime.getRuntime().exec("afplay " + filePath);
But I'd prefer a Java solution. Any ideas?
For JavaFX
You can have a look here Getting a mp3 file to play using javafx
Here you are,my favourite part:
You can use JLayer which supports .mp3.
Example
new Thread(()->{
try {
FileInputStream file = new FileInputStream("path ..../audio.mp3"); //initialize the FileInputStream
Player player= new Player(file); //initialize the player
player.play(); //start the player
} catch (Exception e) {
e.printStackTrace();
}
}).start();
Note:
Note that i am using a separate Thread cause if not the application will stack.
Generally Speaking:
You have to use external libraries to play files like .mp3 in Java(although JavaFX supports .mp3 but not all formats)
Java supports only .wav
Although that's enough.All you need is an external algorithm to play other music formats.All the other format's come originally from .wav,they pass into an algorithm and then boom they become .ogg,.mp3,.whatever
1.As mentioned before for .mp3 JLayer.jar
You can import this jar into your project as an external library.
2.JavaZoom has also and other libraries to support .ogg,.speex,.flac,.mp3,follow the link above and download the jlGui project there you can find libraries for a lot of formats.
Link to stackoverflow on
How to play .wav files with java
And http://alvinalexander.com/java/java-audio-example-java-au-play-sound
Not sure if that still works with java 8
Code:
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.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayerExample1 implements LineListener {
/**
* this flag indicates whether the playback completes or not.
*/
boolean playCompleted;
/**
* Play a given audio file.
* #param audioFilePath Path of the audio file.
*/
void play() {
File audioFile = new File("C:/Users/Alex.hp/Desktop/Musc/audio.wav");
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
audioClip.start();
while (!playCompleted) {
// wait for the playback completes
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
audioClip.close();
} 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();
}
}
/**
* Listens to the START and STOP events of the audio line.
*/
#Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
System.out.println("Playback started.");
} else if (type == LineEvent.Type.STOP) {
playCompleted = true;
System.out.println("Playback completed.");
}
}
public static void main(String[] args) {
AudioPlayerExample1 player = new AudioPlayerExample1();
player.play();
}
}
Kind of a noob to coding, but I've been creating Pacman for a computer science class, and for some reason, I cannot get my audio to work.
Basically, here is the just of what I have written.
public void paint(Graphics g)
{
PlayAudio();
//.... a lot of other stuff
}
My PlayAudio method:
public void PlayAudio()
{
try
{
Clip clickClip = AudioSystem.getClip();
File filePath = new File("opening.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(filePath);
clickClip.open(ais);
clickClip.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
It compile and executes, but the audio file does not play. Thanks for the help!
I have confirmed that my opening.wav:
Is a .wav file.
Has the right name.
Is in the same directory.
Java 7 include new classes to play audio. Media and MediaPlayer. Example:
String media = "media.mp3";
Media hit = new Media(media);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
you need this libreries :
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
But, this will only play .wav files.
The same with:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
I want to be able to play both .mp3 files and .wav files with the same method.
Java FX has Media and MediaPlayer classes which will play mp3 files.
Example code:
String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
You will need the following import statements:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
I wrote a pure java mp3 player: mp3transform.
Using standard javax.sound API, lightweight Maven dependencies, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:
pom.xml:
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
Code:
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.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
References:
http://odoepner.wordpress.com/2013/07/19/play-mp3-using-javax-sound-sampled-api-and-mp3spi/
you can play .wav only with java API:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
code:
AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
And play .mp3 with jLayer
It's been a while since I used it, but JavaLayer is great for MP3 playback
I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX.
http://www.javazoom.net/jlgui/api.html
After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:
basicplayer3.0.jar
all the jars from the lib directory (inside BasicPlayer3.0)
Here is a minimalistic usage example:
String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
player.open(new URL("file:///" + pathToMp3));
player.play();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
Required imports:
import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.
For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html
The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp).
It demonstrates the advanced features of the BasicPlayer pretty well.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
very low CPU usage (~2%)
incredible small library (~90KB)
doesn't need JMF (Java Media Framework)
easy to integrate in any application
easy to integrate in any web page (as applet).
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
UPDATE(2022)
The download link at that page does not work anymore, but there is a sourceforge project
Using MP3 Decoder/player/converter Maven Dependency.
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class PlayAudio{
public static void main(String[] args) throws FileNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream("mp.mp3");
Player player = new Player((fileInputStream));
player.play();
System.out.println("Song is playing");
while(true){
System.out.println(player.getPosition());
}
}catch (Exception e){
System.out.println(e);
}
}
}
You need to install JMF first (download using this link)
File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();
don't forget to add JMF jar files
Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.
You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.
To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.
Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.
I have other methods for that, the first is :
public static void playAudio(String filePath){
try{
InputStream mus = new FileInputStream(new File(filePath));
AudioStream aud = new AudioStream(mus);
}catch(Exception e){
JOptionPane.showMessageDialig(null, "You have an Error");
}
And the second is :
try{
JFXPanel x = JFXPanel();
String u = new File("021.mp3").toURI().toString();
new MediaPlayer(new Media(u)).play();
} catch(Exception e){
JOPtionPane.showMessageDialog(null, e);
}
And if we want to make loop to this audio we use this method.
try{
AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
AudioPlayer.player.start(s);
} catch(Exception ex){
JOPtionPane.showMessageDialog(null, ex);
}
if we want to stop this loop we add this libreries in the try:
AudioPlayer.player.stop(s);
for this third method we add the folowing imports :
import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
Nothing worked. but this one perfectly 👌
google and download Jlayer library first.
import javazoom.jl.player.Player;
import java.io.FileInputStream;
public class MusicPlay {
public static void main(String[] args) {
try{
FileInputStream fs = new FileInputStream("audio_file_path.mp3");
Player player = new Player(fs);
player.play();
} catch (Exception e){
// catch exceptions.
}
}
}
Use this library: import sun.audio.*;
public void Sound(String Path){
try{
InputStream in = new FileInputStream(new File(Path));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e){}
}