I need to be able to play ALAW files in a Java (desktop) application.
I've tried to follow the example at:
How to play audio in Java Application
I've created a File object from the ALAW file (which exists, according to check) and sent that File to a method where the first thing that happens is this:
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
But this is where the execution stops, since I get this exception:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
I see that there is a way to convert ALAW files if the check (ais.getFormat().getEncoding() == AudioFormat.Encoding.ALAW) is true, but how can I get there if it's not even possible to create the AudioInputStream?
Anyone who has worked with ALAW files and has an idea of what I should do?
Is there a way to convert the ALAW files programmatically before calling AudioSystem.getAudioInputStream(file)?
I really need to make this work!
Get existing file format from your AudioInputStream:
filepath is String with path to your file,which you obtain for example:
String filename="x.y";
File file = new File(filename);
String filepath=file.getCanonicalPath();
Then main conversion is done by:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(filepath));
AudioFormat format = inputStream.getFormat();
AudioInputStream convertedInputStream;
After that put condition, which checks if your file encoding is alaw or ulaw, and converts it to PCM which can be played by SoundCard:
if ((format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW))
AudioFormat tmp = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2,
format.getChannels(),
format.getFrameSize() * 2,
format.getFrameRate(), true);
convertedInputStream = AudioSystem.getAudioInputStream(tmp,inputStream);
format = tmp;}
This code will convert ALAW/ULAW format of your AudioInputStream to PCM_SIGNED
JMF will help in this case.
http://www2.sys-con.com/itsg/virtualcd/java/archives/0503/decarmo/index.html
Related
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
Reading about the javasound tag earlier today, I tried to implement the simple code that we can see there (with some minor modifications, such as using File instead of URL):
File file = new File(System.getProperty("user.dir") + "/sound.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
clip.open(ais); // exception
But I'm getting a java.lang.IllegalArgumentException: Invalid format when I try to open the AudioInputStream that we see there.
However, when I try it with the following code that I got from the internet
File file = new File(System.getProperty("user.dir") + "/sound.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
AudioFormat format = ais.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(ais);
clip.start();
it does work: sound.wav is played correctly - however, I find this to be clunky for something that should be as simple as our first example, given on the javasound tag itself.
By reading the documentation from clip, I acknowledged that IllegalArgumentException is thrown when [...] the stream's audio format is not fully specified or invalid. However, it does seem to be a valid format.
What is wrong with our first example here? AudioSystem.getAudioInputStream() does accept a File as argument, and, as visible from the second example, it does appear to have valid audio file data, because it works. Am I missing something obvious? And, if so, shouldn't it be pointed out on javasound tag?
After some research I found out that it could have something to do with the system properties. In those properties you can specify defaults for the getLine() methods (getLine(), getClip(), getSourceDataLine() and getTargetDataLine()). If you call one of these methods, Java does the following (AudioSystem description):
The system property javax.sound.sampled.Clip is set to
javax.sound.sampled.Clip = great.Mixer#great.clip.Clap
The Mixer class is called great.Mixer and the Clip is called great.clip.Clap
When you request a Clip, Java checks the following:
If the Mixer great.Mixer is found and contains the Clip great.clip.Clap, return this Clip
If the Mixer great.Mixer is found, but does not contain the Clip great.clip.Clap, return the first Clip specified in the Mixer
If the Mixer great.Mixer does not contain any Clips or if it isn't found, return the first instance of great.clip.Clap in any Mixer
If no Mixer contains great.clip.Clap, return the first Clip of the first Mixer found
If no Clip is specified in any Mixer, throw an IllegalArgumentException
What that means is that if you are getting an IllegalArgumentException, no Clips are installed in any Mixers.
With
DataLine.Info info = new DataLine.Info(Clip.class, format);
you are defining a new Clip. Which means your next Call to a getLine() method will return this object instead of giving you an error.
To stream audio file I have implemented following code. But i am getting Exception:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1170)
Can Any one help me please......
try {
// From file
System.out.println("hhhhhhhhhhhhhhhh");
AudioInputStream stream = AudioSystem.getAudioInputStream(new File("C:\\track1.mp3"));
System.out.println("stream created");
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
System.out.println("in if");
format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits()*2,
format.getChannels(),
format.getFrameSize()*2,
format.getFrameRate(),
true); // big endian
stream = AudioSystem.getAudioInputStream(format, stream);
}
// Create line
SourceDataLine.Info info = new DataLine.Info(
SourceDataLine.class, stream.getFormat(),
((int)stream.getFrameLength()*format.getFrameSize()));
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(stream.getFormat());
line.start();
// Continuously read and play chunks of audio
int numRead = 0;
byte[] buf = new byte[line.getBufferSize()];
while ((numRead = stream.read(buf, 0, buf.length)) >= 0) {
int offset = 0;
while (offset < numRead) {
offset += line.write(buf, offset, numRead-offset);
}
}
line.drain();
line.stop();
}
That you're doing this job in a servlet class gives me the impression that your intent is to play the mp3 file whenever someone visits your website and that the visitor should hear this mp3 file.
If true, I'm sorry to say, but you're approaching this entirely wrong. Java servlet code runs in webserver machine and not in webbrowser machine. Whenever someone visits your website, this way the mp3 file would only be played at the webserver machine. This is usually a physically completely different machine which runs at the other side of the network connection and the visitor ain't ever going to hear the music.
You want to send the mp3 file raw (unmodified byte by byte) from webserver to the webbrowser without massaging it by some Java Audio API and instruct the webbrowser to play this file. The easist way is to just drop the mp3 file in public webcontent (there where your HTML/JSP files also are) and use HTML <embed> tag to embed it in your HTML/JSP file. The below example assumes the MP3 file to be in the same folder as the HTML/JSP file:
<embed src="file.mp3" autostart="true"></embed>
That's all and this is supported in practically every browser and it will show a player as well.
If the MP3 file is by business requirement stored outside public webcontent, then you may indeed need a servlet for this, but the servlet should do absolutely nothing more than getting an InputStream of it in some way and write it unmodified to the OutputStream of the HttpServletResponse the usual Java IO way. You only need to set the HTTP Content-Type header to audio/mpeg beforehand and if possible also the HTTP Content-Length header. Then point the src to the servlet's URL instead.
<embed src="mp3servlet" autostart="true"></embed>
Default java AudioInputStream does not support mp3 files. You have to plug in MP3SPI to let it decode mp3.
ALso, what do you mean by streaming? This code will play the audio file, not stream it as in internet radio streaming.
What I'm trying to do is when a user hits a link with the correct parameters, the system will retrieve the file from the MS Server 2005 db and outputs it to the user. Specifically, I stored an audio file in varbinary data type and now I have the ID to retrieve the audio file but I don't know what is the Java command to output it for the user.
My code is written in Java and I tried to search for a similar topic on here but had no luck. Any help is appreciated.
Thanks
-Bao
There is one example for file downloading here, maybe is helpful:
http://www.daniweb.com/software-development/java/threads/154128
Maybe you can try to combine that with your link handler.
I figured it out. This is the solution that did the job for me. Basically I had to use the javax.sound.sampled.* API. This is what I did below:
InputParameters parameters = parts.getParameters();
int audioFileID = parameters.getIntParameter("audiofileID");
//Retrieves Audio File
AudioFile audioFile = CallManager.getAudioFile(audioFileID);
InputStream is = new ByteArrayInputStream(audioFile.getAudio());
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(is);
ServletOutputStream out = response.getOutputStream();
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
AudioFormat format = audioInputStream.getFormat();
audioInputStream = AudioSystem.getAudioInputStream(format, audioInputStream);
}
AudioSystem.write(audioInputStream,javax.sound.sampled.AudioFileFormat.Type.WAVE,byteOutputStream);
I'm working on an application that has to process audio files. When using mp3 files I'm not sure how to handle data (the data I'm interested in are the the audio bytes, the ones that represent what we hear).
If I'm using a wav file I know I have a 44 bytes header and then the data. When it comes to an mp3, I've read that they are composed by frames, each frame containing a header and audio data. Is it possible to get all the audio data from a mp3 file?
I'm using java (I've added MP3SPI, Jlayer, and Tritonus) and I'm able to get the bytes from the file, but I'm not sure about what these bytes represent or how to handle then.
From the documentation for MP3SPI:
File file = new File(filename);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
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);
You then just read data from din - it will be the "raw" data as per decodedFormat. (See the docs for AudioFormat for more information.)
(Note that this sample code doesn't close the stream or anything like that - use appropriate try/finally blocks as normal.)
The data that you want are the actual samples, while MP3 represents the data differently. So, like what everyone else has said - you need a library to decode the MP3 data into actual samples for your purpose.
As mentioned in the other answers, you need a decoder to decode MP3 into regular audio samples.
One popular option would be JavaLayer (LGPL).