run mp3 and .aac vlc audio in java - java

I would like to run audio file from java and i read many codes in SO but unbale to run my file perhaps!
Seems I have mentioned wrong path or using wrong lib .
Please assist me what's wrong in below code to run mp3 or VLC .aac format file
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/clinic/clinic/mysound.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}

If you use the this.getClass.getResource() method instead of the File(file) method, maybe it would work. Remember that the file that the audio is in has to be in the same package as the class that is running it. If this doesn't work, then try it with a .wav file(you can use a .mp3 to .wav converter).
public void run() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("mysound.mp3"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception ex) {
ex.printStackTrace();
}
}
I hope this helps.

AudioSystem does not support .mp3 files. (Only AIFC, AIFF, AU, SND, and WAVE)
If you want to use .mp3 files, try using MediaPlayer instead.
// Fake init of JFX Toolkit (Just do this once before you use MediaPlayer)
// Not needed in a JavaFX application as Application.launch() inits the toolkit
new JFXPanel();
Media media = new Media(new File("yourFile.mp3").toURI().toString());
MediaPlayer player = new MediaPlayer(media);
player.play();

The audioformats supported natively are nit that useful if you don't want to have huge audiofiles.
I ended using WAV files as it was what I could get to work, but it bothered me all the time.
Using jaad was trickier than I thought, but I got it working now: Java play AAC encoded audio

Related

FIle Sound not found, and return java.lang.NullPointer Exception

I have tried putting the .wav file on the separate modules title sound, putting it in the same packages with the program, and putting it in src. I checked using command prompt and the file is playable. I also make sure that .wav is supported by Java. What I'm confused about is, it did not return FileNotFound exception, but NullPointer Exception. What is it that I am doing wrong? Beforehand, thank you for those who can help.
Here is my source code:
Clip brickCollisionSound;
Clip gameMusicSound;
Clip gameWinSound;
Clip paddleCollisionSound;
Clip wallCollisionSound;
private void initSounds() {
try {
File soundFile = new File("./gameOver.wav");
//URL url = this.getClass().getClassLoader().getResource("sound/gameOver.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
gameOverSound = AudioSystem.getClip();
gameOverSound.open(audioIn);
soundFile = new File("./BrickCollission.wav");
//url = this.getClass().getClassLoader().getResource("sound/BrickCollission.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
brickCollisionSound = AudioSystem.getClip();
brickCollisionSound.open(audioIn);
soundFile = new File("./gameMusic.wav");
//url = this.getClass().getClassLoader().getResource("sound/gameMusic.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
gameMusicSound = AudioSystem.getClip();
gameMusicSound.open(audioIn);
soundFile = new File("./gameWin.wav");
//url = this.getClass().getClassLoader().getResource("sound/gameWin.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
gameWinSound = AudioSystem.getClip();
gameWinSound.open(audioIn);
soundFile = new File("./PaddleCollision.wav");
//url = this.getClass().getClassLoader().getResource("sound/PaddleCollision.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
paddleCollisionSound = AudioSystem.getClip();
paddleCollisionSound.open(audioIn);
soundFile = new File("./WallCollision.wav");
//url = this.getClass().getClassLoader().getResource("sound/WallCollision.wav");
audioIn = AudioSystem.getAudioInputStream(soundFile);
wallCollisionSound = AudioSystem.getClip();
wallCollisionSound.open(audioIn);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
}
}
public void playMusic() {
gameMusicSound.setMicrosecondPosition(0);
gameMusicSound.start();
gameMusicSound.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stopMusic() {
if (gameMusicSound.isRunning()) gameMusicSound.stop();
}
public void playGameOverSound() {
gameOverSound.setMicrosecondPosition(0);
gameOverSound.start();
}
public void playGameWinSound() {
gameWinSound.setMicrosecondPosition(0);
gameWinSound.start();
}
public void playBrickCollisionSound() {
brickCollisionSound.setMicrosecondPosition(0);
brickCollisionSound.start();
}
public void playPaddleCollisionSound() {
paddleCollisionSound.setMicrosecondPosition(0);
paddleCollisionSound.start();
}
public void playWallCollisionSound() {
wallCollisionSound.setMicrosecondPosition(0);
wallCollisionSound.start();
}
```
File soundFile = new File("./gameOver.wav");
this attempts to find that file in the 'current working directory'. What that is depends on the user, and thus, this isn't how you do that. Delete these lines.
URL url = this.getClass().getClassLoader().getResource("sound/gameOver.wav");
That's also not how you do that.
It's:
package com.foo;
class Foobar {
private void initSounds() {
Foobar.class.getResource("sounds/gameOver.wav");
}
}
This looks for a directory named sounds which should be in the same place that the file Foobar.class is in (even if it is in a jar or jmod file, that's fine). In other words, if you have a jar with that, you'd have com/foo/Foobar.class and com/foo/sounds/gameOver.wav in that jar file. If you prefer to from the root of the jar, you can do that: .getResource("/sounds/gameOver.wav") (note the leading slash) would look in the same jar/dir/etc. So if your Foobar.class is currently running from /Users/Khaela/workspace/game-project/bin/com/foo/Foobar.class, then the sounds file is looked for in /Users/Khaela/workspace/game-project/bin/sound/gameOver.wav.
Note that maven and most other build tools copy the files from src/main/resources over the same way that IDEs and tools compile files over from src/main/java. Thus, put them there (if using .getResource("sounds/gameOver.wav"), make sure src/main/resources/foo/bar/gameOver.wav exists). IDEs with maven plugins will figure it out and make it work, too.
} catch (UnsupportedAudioFileException | IOException | >LineUnavailableException e) {
}
This is incredibly silly code. Don't catch exceptions if you don't know what to do (unless you rethrow them), and definitely don't catch exceptions and completely ignore them. It's confused you so much it led you to asking questions on SO. Do not write catch blocks like this.
The right 'I dunno what to do!' catch block is this:
} catch (SomethingYouHaveNoClueAbout e) {
throw new RuntimeException("Uncaught", e);
}
This ends execution (you want that - bad things happened, don't just continue on blindly, with half of the code you ran so far not having done what you wanted it to do, and no idea which half or what failed - continuing on with code execution is a very bad idea under those circumstances, obviously) - and preserves ALL information about the problem (which is a lot: Message, exception type, stack trace, causal chain, suppressed list, and depending on the exception even more info).

How can I play audio in java with command line interface?

I have been searching for how to play audio in java ( textpad ). There are plenty of examples but they use a GUI. I am using a command line interface. How do I play audio and use key event e.g spacebar to pause the audio and press spacebar again to replay the audio?
I do not know which examples you have been looking at but I do not think the GUI has anything to do with IF you can play sounds.
The following code is a simple sound class you can use in order to play audio in Java, you can read more about it at this Documentation.
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;
public class Sound {
private URL url;
private Clip clip;
/**
* #param requestedSound The requested type of sound
*/
public Sound(String requestedSound) {
url = this.getClass().getResource(requestedSound);
if (url != null) {
try {
// Open an audio input stream.
// Get a sound clip resource.
// Open audio clip and load samples from the audio input stream.
AudioInputStream audioInput = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(audioInput);
} catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
e.printStackTrace();
}
}
}
/**
* Plays the sound
*/
public void play() {
clip.setFramePosition(0);
clip.start();
}
}
To use it you simply create a sound in your main file, with Sound mySound = new Sound("path_to_sound"); Where you replace path_to_sound with your path. I believe one of the supported formats is .wav. Then you can just play the sound whenever you want to with mySound.play();, and whenever you do it will be played from the beginning.
Regarding your implementation of using spacebar to play / replay the audio, I believe it is better if you try to work with the given code in order to understand how it works.

Audio not playing with JAR File

I created a project that plays audio within the netbeans IDE. Those audio files were placed in the Classes folder.
Although when I created it as a JAR file, it was unable to locate the audio files. I even copy and pasted the files inside the new dist folder.
Here is a snippet of code:
private void playSound39()
{
try
{
/**Sound player code from:
http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("./beep39.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Audio file not found!");
}
}
If you want to embedd the audio file in your program it's must be placed inside the src folder in a package.
For example I'll demonstrate a code I use to set icons to buttons (should work for audio files as well) :
While creating the JFrame I wrote :
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Icon/PatientBig.png")));
I have in my project a package called GUI with a subpackage called Icons where my icons exist and they all are in src folder.
When you using getClass().getResource function , I prefer to use an absolute path.
After seeing your respone I have noticed that you keep using . in the begining of the class path, I copied the snippet you published and removed the . from the begining of the path and placed my audio file bark.wav in the src folder in the default package and it worked
public class test {
private void playSound39() {
try {
/**
* Sound player code from:
* http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("/bark.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Audio file not found!");
}
}
public static void main(String[] args){
new test().playSound39();
}
}
Then I placed the audio file inside a package called test1 and modified the path in getResourceAsStream function and again it worked:
public class test {
private void playSound39() {
try {
/**
* Sound player code from:
* http://alvinalexander.com/java/java-audio-example-java-au-play-sound
*/
// the input stream portion of this recipe comes from a javaworld.com article.
InputStream inputStream = getClass().getResourceAsStream("/test1/bark.wav");
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Audio file not found!");
}
}
public static void main(String[] args){
new test().playSound39();
}
}
The Most important thing is to remove . from the path
try this
InputStream in = getClass().getResourceAsStream("/beep39.wav");
I think you need to bypass use of the InputStream. When running the getAudioInputStream method, using InputStream as a parameter triggers markability and resetability tests on the audio file. Audio files usually fail these tests. If you create your AudioInputStream with a URL or File parameter, these tests are circumvented. I prefer URL as it seems more robust and can "see into" jars.
URL url = getClass().getResource("./beep39.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
Then, in a while loop, you would execute a read method on the AudioInputStream and send the data to a SourceDataLine.
The Java Tutorials covers this in their audio trail. This link jumps into the middle of the tutorials.
AFAIK, there is no "AudioPlayer" in the Java 7 SDK.

Computer can't find 'AudioStream' when wanting to play background music for an app

So what I have tried to do is make my application play music in the background with a .wav music file.
I have this code but AudioStream can't be found under
sun.audio.*;
If any of you have worked with Eclipse IDE, how would you be able to find AudioStream to import it...
Here's my code which this uses. It's under the Sound class which doesn't implement or extend anything.
private AudioStream as;
private String lastSoundPath;
private void setStream(String soundPath){
this.lastSoundPath = soundPath;
try {
InputStream in = new FileInputStream(soundPath);
this.as = new AudioStream(in);
} catch (Exception e) {
e.printStackTrace();
}
}
Here's the error I get when trying to play Bangarang (Random I know...)
java.io.IOException: could not create audio stream from input stream
at sun.audio.AudioStream.<init>(AudioStream.java:82)
at vapour.studios.destiny.client.Sound.setStream(Sound.java:17)
at vapour.studios.destiny.client.Sound.<init>(Sound.java:24)
at vapour.studios.destiny.Destiny.main(Destiny.java:23)
Thanks in advance.
You need to use javaSE 1.7 as execution environment in project properties.
it worked for me on Mac OS 10.8

How to play a WAV in Java, when the WAV is contained inside the JAR

I've been trying to deal with sound on my Applet for a bit now, and Instead of trying all the different methods, what is the best way to play Sound in Java? There are a few requirements:
Needs to be able to loop
Needs to be able to load a WAV from an archive JAR(I think with the getClass().getResource)
Needs to be able to play more than one sound at the same time, and not clip already playing sounds
Thanks you so much for looking at my question and I hope you guys have an answer!
Thanks to the wonderful help I almost have it working with this:
public class MyGame() {
Clip bullet;
public void init(){
try {
bullet = AudioSystem.getClip();
URL url2 = this.getClass().getResource("bulletSound.wav");
AudioInputStream ais2 = AudioSystem.getAudioInputStream( url2 );
bullet.open(ais2);
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
randomMethodToPlayBullet(){
bullet.setFramePosition(0);
bullet.start();
}
}
The problem is that the bullet sound plays, but if the randomMethodToPlayBullet is called say twice in a row, before the first bullet sound is done, the seonc one doesnt play.
The best way to load resources from jar file is to put in the same folder a class and get the resource with .class.getResource(...) or .class.getResourceaAsStream(...) methods:
URL url = ClazzInTheFolderOfMyMidiFile.class.getResource(nameOfMidiFile);
or
InputStream resourceAsStream = ClazzInTheFolderOfMyMidiFile.class.getResourceAsStream(nameOfMidiFile);
The answer for:
Small samples is Clip. See the Java Sound info. page for an example of use.
Large samples is BigClip.
You can't play the same Clip twice at the same time. You have to create another instance of Clip to play the sound twice at the same time.
Note that there will be a limit how many clips you can play, so the clip API may not be suited to support a sound-heavy game.

Categories