Trying to play a sound file - java

I am having some problems with this code, I am trying to play the sound file but it is not working.
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
public class DiscoMusic
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://www.lecons-guitare.com/Audio/Backingtracks/Stayin_alive.mp3");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
}
}

According to the JavaSound info. page.
MP3 decoding support
The Java Sound API does not support many formats of sampled sound
internally. In a 1.6.0_24 Oracle JRE getAudioFileTypes() will
generally return {WAVE, AU, AIFF}. An MP3 decoder at least, is close
by. The mp3plugin.jar of the Java Media Framework supports decoding
MP3s.
I can vouch for that information since I've successfully loaded MP3s using Java Sound and the MP3 SPI (& also wrote the info. page ;) ). The JMF installer download is becoming hard to find, but you can get the mp3plugin.jar direct from where I put it for use in JWS apps.

Related

Playing a song in java [duplicate]

This question already has an answer here:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file when loading wav file
(1 answer)
Closed 8 years ago.
I want to play a audio clip from my computer while a game is playing. But i can only use very very short sounds. Is there any similar way to playing songs like i play sound effects?
Im using swing graphics for the game if that matters.
The error i get when i try to use a song
"javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file"
public static void main(String args[]) {
Sound s = new Sound();
s.playSound("C:/Users/isac/Desktop/banjos.wav");
}
}
public void playSound(String file) {
try {
AudioInputStream audio = AudioSystem.getAudioInputStream(new File(
file));
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
}
catch (UnsupportedAudioFileException uae) {
System.out.println(uae);
} catch (IOException ioe) {
System.out.println(ioe);
} catch (LineUnavailableException lua) {
System.out.println(lua);
}
}
}
The error message you are getting indicates the problem is probably with the format of the file, not its length.
You can check the format of an audio file by looking at it's properties--usually requires a right click on Windows. The properties that matter may be on an "Advanced" tab. Java can read many formats, but where I've most often seen it hang up is with the following:
a person tries to load a .mp3 or .ogg or other form of compression but hasn't implemented any libraries that can decompress those files (not your situation, since your banjo.wav is a wav).
the .wav is not the standard "CD Quality" format (44100 fps, 16-bit encoding, stereo) but rather something like 24-bit or 32-bit encoding or 48000 or 96000 fps.
Current DAWs often make it easy to record in formats that are superior to "CD Quality" but Java doesn't support them yet.
For the most part, you can convert audio files that are not readable with Java to one that is with Audacity (free), if you aren't working from another home studio program. Be careful where you obtain Audacity as some sites that provide it (other than the official site) will include adware or malware or viruses.
As a side note, for a longer file, it would be better to load into a SourceDataLine for playback instead of a Clip. With a SourceDataLine, you don't have to wait for the entire file to load before it will start playing back, and it won't take up anywhere near as much RAM. The Java Tutorials has a section for Java Sound and a page there specifically on playback.

best approach for extract / extracting images / image sequence from videos / video file in Java

Well, there is FFMPEG and some Java bindings and wrappers for it but I need to distribute for each specific platform the right binary file of FFMPEG.
Isnt there any plain Java solution or library without any dependencies like FFMPEG for converting a video fle to an image sequence?
Solutions like FFMPEG, XUGGLER or JMF (abandoned) are not suitable. Is there really no pure Java solution for this?
Maybe for specific video codecs / files at least?
I just want to extract the images from the video file to jpeg / png files and save them to the disk
Is there really no pure Java solution for [extracting images from a video stream]?
Let's see. You have to:
Decode the video.
Present the decoded images at least as fast as 24 images / second. I suppose you can skip this step.
Save the decoded images.
It appears that decoding the video would be the most challenging step. People and companies have spent years developing codecs (encoder / decoder) for various video formats.
There's a project on SourceForge, JMF wrapper for ffmpeg, that has developed a few pure Java video codecs. Perhaps you can look at their source code and see how to develop a Java video codec for yourself.
You can look for other pure Java video codecs if you wish.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber.Exception;
public class Read{
public static void main(String []args) throws IOException, Exception, InterruptedException, ExecutionException
{
FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("C:/Users/Digilog/Downloads/Test.mp4");
frameGrabber.start();
IplImage i;
try {
for(int ii=0;ii<frameGrabber.getLengthInFrames();ii++){
i = frameGrabber.grab();
BufferedImage bi = i.getBufferedImage();
String path = "D:/Image/Image"+ii+".png";
ImageIO.write(bi,"png", new File(path));
}
frameGrabber.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is a pure Java implementation of the following codecs: H.264 ( AVC ), MPEG 1/2, Apple ProRes, JPEG; and the following file formats: MP4 ( ISO BMF, QuickTime ), Matroska, MPEG PS and MPEG TS.
The library is called JCodec ( http://www.jcodec.org ).
It has very little documentation for now but the development team is constantly working on this.
Here's how you can simply grab a frame from an MP4 file ( sample from their web site ):
int frameNumber = 150;
BufferedImage frame = FrameGrab.getFrame(new File("filename.mp4"), frameNumber);
ImageIO.write(frame, "png", new File("frame_150.png"));
To add JCodec to your project you can simply add below to your pom.xml:
<dependency>
<groupId>org.jcodec</groupId>
<artifactId>jcodec</artifactId>
<version>0.1.3</version>
</dependency>
For latest version, see here.

I can not use JMF

Now I am trying with another sound file with mp3 codec. But I am encounterring problem to start the player.
I have downloaded the file from http://www.mediacollege.com/audio/tone/download/
The output from Netbeans is:
run: Error: Unable to realize com.sun.media.amovie.AMController#ebf3f0 BUILD SUCCESSFUL (total time: 2 seconds)
And my program is:
import javax.media.*;
import java.io.*;
public class MP3Player {
public static void main(String[] args) throws Exception
{
File file = new File("c:/player/sound.mp3");
MediaLocator mrl = new MediaLocator(file.toURL());
Player player = Manager.createPlayer(mrl);
player.start();
Thread.sleep(1000);
}
}
JMF does not support the mp3 format due to licensing issues.
This article on extending JavaSound to Play MP3 should give you everything that you need, including a place to download an mp3 codec. I have recently used this sample code as the basis for an mp3 player, and used it on both Windows and OS X, and I can verify that it works very well.
Try using this:
String theFile = "file:///c:/player/sound.mp3";
MediaLocator mrl = new MediaLocator(theFile);
works good for me..

could not get audio input stream from input URL

I am trying to run a sound file in Java using this code:
public class Audio3
{
public static void main(String[] args) throws Exception
{
URL soundFile =new URL(
"http://everyayah.com/data/Ghamadi_40kbps/audhubillah.mp3");
AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
AudioPlayer.player.start(ais);
}
}
I am getting this exception
javax.sound.sampled.UnsupportedAudioFileException:
could not get audio input stream from input URL
Any idea what could be the reason?
According to the JavaSound info. page.
MP3 decoding support
The Java Sound API does not support many formats of sampled sound internally. In a 1.6.0_24 Oracle JRE getAudioFileTypes() will generally return {WAVE, AU, AIFF}. An MP3 decoder at least, is close by. The mp3plugin.jar of the Java Media Framework supports decoding MP3s.
I can vouch for that information since I've successfully loaded MP3s using Java Sound and the MP3 SPI (& also wrote the info. page ;) ). The JMF installer download is becoming hard to find, but you can get the mp3plugin.jar direct from where I put it for use in JWS apps.

Get File from Main.class.getResource()

I am making a small game in Java. For this game I just added sounds. So I want to have all my images and audio files in the jar. For pictures this was easy:
new ImageIcon(Main.class.getResource("images/machgd2.png")).getImage()
But for audio it only works when I run the program in Eclipse but not from a jar. I use:
File soundFile = new File(Main.class.getResource(filename).getFile());
So how can I get this file from inside the .jar file?
Update:
OK, got it working, thanks to Andrew!
To play the sound I used a class I found on the net, and I found out that class just uses File to get an AudioInputStream, so I dropped the File thing.
When it's in a jar file, it isn't a file on the file system, is it? You'll either have to copy the file out of the jar file into some temporary location, or use APIs which don't require a file (e.g. ones which only need an InputStream or a URL, both of which are easily available from jar files using getResourceAsStream or getResource.).
You haven't shown where you're using soundFile - if you show us which APIs you're trying to use, we can try to suggest an appropriate alternative.
See "Playing a Clip" from the Java Sound info page here at SO to see..
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);
// loop continuously
clip.loop(-1);
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!");
}
});
}
}
Which, you might notice, uses an URL (as returned by getResource()) rather than a File. The method is overloaded to also accept File or InputStream, but I use the URL based version most commonly.

Categories

Resources