could not get audio input stream from input file - java

I want to play the mp3 file in java. I am using a code but show the exception could not get audio input stream from input file.
My source code is :
try {
System.out.println("Start");
File f = new File("E:\\malayalam good song\\01_ISHTAMANU.MP3");
AudioInputStream audio = AudioSystem.getAudioInputStream(f);
System.out.println("Start");
AudioFormat format = audio.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[524288];
while (nBytesRead != -1) {
nBytesRead = audio.read(abData, 0, abData.length);
if (nBytesRead >= 0) {
auline.write(abData, 0, nBytesRead);
}
}
} catch (Exception E) {
System.out.println("Exception"+E.getMessage());
}

Add mp3plugin.jar in your classpath.
http://pscode.org/lib/mp3plugin.jar

If you are on java 7, there are new (JavaFX) classes there that are easier to use:
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
...
...
try {
File f = new File("E:\\malayalam good song\\01_ISHTAMANU.MP3");
Media hit = new Media(f.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
} catch(Exception ex) {
ex.printStackTrace();
System.out.println("Exception: " + ex.getMessage());
}
If you are not on Java 7, you can grab JavaFX jars from here.

You should convert wav audio files to 8khz, 16 bit, mono PCM in uncompressed format. Then it will work.

Dudes, I passed a night matter with this exception, man it was hard to find a solution, first of all, you will not need to alter your code or same thing like that at majority of the cases, you just need to convert the format of wav that you have, following this tutorial: here
But the thread started here
After that I had another problem, basically it was saying that I can't play the sound because iceadtea-sound was not in library and yeah man, to solve that I runned a command:
apt-get install openjdk-8-jre openjdk-8-jdk
that I get on here
And after this bug solved I come across another one named "Invalid format with getAudioInputStream, trying to play a sound in Java"
That bug I solved with this answer here on stackoverflow here
And after this, finally a song was played

Related

Playing audio files from a JAR-application does not work on Linux

I need some help with my Java application. Its purpose is to read a certain website, so I need to play many audio files in a row. The JAR is compiled using Java 8. I tested my application with Windows 11 and Java 16.0.1, everything works fine. Then I used the latest Ubuntu Linux and Java 11.0.13 as well as Java 8: It plays some audio, but not every file.
I wrote a test class and the result was, that - no matter in which order I play the audio - only the first (exactly!) 62 files are played. Every next file (even the ones, that were successfully played at first) produces the exception my code throws at this position:
if (mixerSelected != null) {
audioClip0 = AudioSystem.getClip(mixerSelected);
} else {
throw new IllegalArgumentException("File is not compatible: '" + audioFilePath + "'.");
}
I ensured that every audio file is .WAV with
8k sample rate,
16k Bytes per second in average,
16 Bits, and
pcm_s16le codec.
My application is built as JAR-file including my audio files in the resources directory.
This is my code:
public class PlayAudio {
/**
* plays an audio file
*
* #param audioFilePath String: path to the audio file
* #param speed double: speed applied to the audios
*/
public boolean singleFile(String audioFilePath, double speed) {
//audioFilePath = "audio" + File.separator + audioFilePath;
audioFilePath = "audio" + "/" + audioFilePath;
AudioInputStream audioStream0;
//create new file using path to the audio
try {
//load files from resources folder as stream
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(audioFilePath);
InputStream bufferedInputStream = new BufferedInputStream(inputStream);
if (bufferedInputStream == null) {
throw new IllegalArgumentException("File not found: '" + audioFilePath + "'.");
} else {
//create new AudioStream
audioStream0 = AudioSystem.getAudioInputStream(bufferedInputStream);
}
} catch (IllegalArgumentException e) {
//handle
return false;
} catch (IOException e) {
//handle
return false;
} catch (UnsupportedAudioFileException e) {
//handle
return false;
}
try {
//create new AudioFormat
AudioFormat audioFormat0 = audioStream0.getFormat();
//create new Info
DataLine.Info info0 = new DataLine.Info(Clip.class, audioFormat0);
//initialize new Mixer
Mixer.Info mixerSelected = null;
for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) {
Mixer mixer = AudioSystem.getMixer(mixerInfo);
if (mixer.isLineSupported(info0)) {
mixerSelected = mixerInfo;
break;
}
}
//create new Clip
Clip audioClip0;
if (mixerSelected != null) {
audioClip0 = AudioSystem.getClip(mixerSelected);
} else {
//THIS EXCEPTION GETS THROWN!!!
throw new IllegalArgumentException("File is not compatible: '" + audioFilePath + "'.");
}
//open created Clips via created AudioStream
audioClip0.open(audioStream0);
//start the play of audio file
audioClip0.start();
//wait until play completed
double waitTime = (double)((((double)audioClip0.getMicrosecondLength()/1000.0)/speed + 50.0) * 0.8);
Thread.sleep((long)waitTime);
return true;
//handle exceptions
} catch (LineUnavailableException e) {
//handle
return false;
} catch (IOException e) {
//handle
return false;
} catch (InterruptedException e) {
//handle
return false;
} catch (IllegalArgumentException e) {
//THIS EXCEPTION GETS THROWN!!!
//handle invalid audio clips
System.out.println(e);
e.printStackTrace();
return false;
}
}
/**
* plays multiple audio files in the order they are stored in an ArrayList
*
* #param fileNames ArrayList<String>: list with filenames of audio files to play
* #param speaker String: speaker to use for playing the audios (can be 'm' or 'w')
* #param speed double: speed applied to the audios
* #return boolean: true if playing audios completed successfully, otherwise false
*/
public static boolean multiFiles(ArrayList<String> fileNames, String speaker, double speed) {
PlayAudio player = new PlayAudio();
//play every audio file in the array of file names
for (int i = 0; (i < fileNames.toArray().length); i ++) {
//generate file names
String fullFileName = speaker + "_" + fileNames.toArray()[i];
//play audio
player.singleFile(fullFileName, speed);
}
return true;
}
}
What did I already try?
I tried it on another computer that runs Ubuntu Linux as well.
I created a new instance of PlayAudio() everytime a new audio is played.
I used audioClip0.stop(); after every audio.
I increased the milliseconds of sleep after every audio to length of the audio plus 1 second.
I rebuilt the projects ... nearly 1k times.
How can I reproduce the error?
I simply need to play more than 62 audio files running my JAR-file under Linux Ubuntu.
How can you help me?
I don't know how to handle this issue. What is the problem playing .WAV-files with Linux?
Is there a common way to fix this?
(I am not allowed to use any library except OracleJDK and OpenJDK.)
The #1 suggestion is by Mark Rotteveel. The AudioInputStream class needs closing. This is often a surprise for people, because Java is well known for managing garbage collection. But for AudioInputStream there are resources that need to be released. The API doesn't do an adequate job of pointing this out, imho, but the need for handling can be inferred from the description for the AudioInputStream.close() method:
Closes this audio input stream and releases any system resources
associated with the stream.
The #2 suggestion is from both Andrew Thompson and Hendrik may be more a helpful hint than a direct solution, but it is still a very good idea, and it seems plausible to me that the inefficiency of all the additional, unneeded infrastructure (ClassLoader, InputStream, BufferedInputStream) might be contributing to the issue. But I really don't have a good enough understanding of the underlying code to know how pertinent that is.
However, I think you can do even better. Don't use Clip. You current use of Clip goes against the concept of its design. Clips are meant for short duration sounds that are to be held in memory and played multiple times, not files that are repeatedly reloaded before each playback. The proper class for this sort of use (load and play) is the SourceDataLine.
An example of playback using a SourceDataLine can be found in the javasound wiki. This example also illustrates the use of URL for obtaining the necessary AudioInputStream. I will quote it here verbatim.
public class ExampleSourceDataLine {
public static void main(String[] args) throws Exception {
// Name string uses relative addressing, assumes the resource is
// located in "audio" child folder of folder holding this class.
URL url = ExampleSourceDataLine.class.getResource("audio/371535__robinhood76__06934-distant-ship-horn.wav");
// The wav file named above was obtained from https://freesound.org/people/Robinhood76/sounds/371535/
// and matches the audioFormat.
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
AudioFormat audioFormat = new AudioFormat(
Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);
Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
SourceDataLine sourceDataLine = (SourceDataLine)AudioSystem.getLine(info);
sourceDataLine.open(audioFormat);
int bytesRead = 0;
byte[] buffer = new byte[1024];
sourceDataLine.start();
while((bytesRead = audioInputStream.read(buffer)) != -1)
{
// It is possible at this point manipulate the data in buffer[].
// The write operation blocks while the system plays the sound.
sourceDataLine.write(buffer, 0, bytesRead);
}
sourceDataLine.drain();
// release resources
sourceDataLine.close();
audioInputStream.close();
}
}
You will have to do some editing, as the example was set up to run via a main method. Also, you'll be using your audio format, and that the names of the audio files with their folder locations will have to match the relative or absolute location specified in the argument you use in getResource() method. Also, a larger size for the buffer array might be preferred. (I often use 8192).
But most importantly, notice that in this example, we close both the SourceDataLine and the AudioInputStream. The alternate suggestion to use try-with-resources is a good one and will also release the resources.
If there are difficulties altering the above to fit into your program, I'm sure if you show us what you try, we can help with making it work.
After applying the answer from #Phil Freihofner this worked for me:
/**
* plays an audio file
*
* #param audioFilePath String: path to the audio file
* #param speed double: speed applied to the audios
*/
public boolean singleFile(String audioFilePath) {
//get class
ClassLoader classLoader = getClass().getClassLoader();
//use try-with-resources
//load files from resources folder as stream
try (
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
new BufferedInputStream(
Objects.requireNonNull(classLoader.getResourceAsStream(audioFilePath))))
) {
if (audioInputStream == null) {
throw new IllegalArgumentException("File not found: '" + audioFilePath + "'.");
}
//create new AudioFormat
AudioFormat audioFormat = audioInputStream.getFormat();
//create new Info
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
//create new SourceDataLine and open it
SourceDataLine sourceDataLine = (SourceDataLine)AudioSystem.getLine(info);
sourceDataLine.open(audioFormat);
//start the play of the audio file
int bytesRead;
byte[] buffer = new byte[8192];
sourceDataLine.start();
while ((bytesRead = audioInputStream.read(buffer)) != -1) {
sourceDataLine.write(buffer, 0, bytesRead);
}
sourceDataLine.drain();
sourceDataLine.close();
audioInputStream.close();
//return true, because play finished
return true;
} catch (Exception e) {
//ignore exceptions
return false;
}
}
Thak you all for contributing to my solution.

How do you play a long AudioClip in(&from) JAR(background music)?

I'm doing a pet project (a kind of game). And I ran into a problem: when the application is called from the console with the command:
C:\java -jar MyGame.jar
short sounds are played, but long ones are not.
All sounds are inside the JAR in the "/assets" folder.
The path to the audio looks like this:
C:\MyGame.jar\assets\background_music.wav
Such as a shot or a jump are played. For long audio data, only the first 0.5 seconds are played.
For example: if you load the sound with 0.834 sec length, then it loops (background music), the sound is played in a loop! (WAV file, 0.843 sec, 48 KB).
But if you load a WAV file for 2 seconds and a size of 115 KB, only 0.5-1 seconds are played.
If you load a WAV background music file for 15 seconds (or 7 seconds) and a size of 110 - 2000 KB and more, the same 0.5 seconds will be played. EVERY 15 (or 7) seconds (if you say "play in a loop").
That is, the file is loaded, its length is loaded, markers are placed at the beginning and at the end, but I only hear the first 0.5 seconds of audio (every "x" -sec, where "x" is the length of the clip).
Audio upload method:
public static InputStream uploadAudio (String path){
InputStream sourceSound = null;
try{
final File jarFile = new File(ResourceLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath());
if(jarFile.isFile()) { // Run with JAR file
final JarFile jar = new JarFile(jarFile);
InputStream fileInputStreamReader =(jar.getInputStream(jar.getEntry(path)));
byte[] byteArray = new byte[fileInputStreamReader.available()];
fileInputStreamReader.read(byteArray);
InputStream newInputStreamFromArray = new BufferedInputStream(new ByteArrayInputStream(byteArray));
sourceSound = newInputStreamFromArray;
jar.close();
} else { // Run with IDE
URL url = ResourceLoader.class.getResource( "../" + path);
InputStream fileInputStreamReader = new BufferedInputStream(new FileInputStream(url.getPath()));
sourceSound = fileInputStreamReader;
}
}catch (IOException e){
e.printStackTrace();
}
return sourceSound;
}
Part of the audio playback class:
public class Sound implements AutoCloseable {
private boolean released = false;
private AudioInputStream stream = null;
private Clip clip = null;
private FloatControl volumeControl = null;
private boolean playing = false;
public Sound(InputStream inputStream) {
try {
stream = AudioSystem.getAudioInputStream(inputStream);
clip = AudioSystem.getClip();
clip.open(stream);
clip.addLineListener(new Listener());
volumeControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
released = true;
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException exc) {
exc.printStackTrace();
released = false;
close();
}
}
public void playLoop(boolean breakOld){
if (released) {
if (breakOld) {
clip.stop();
clip.loop(Clip.LOOP_CONTINUOUSLY);
playing = true;
} else if (!isPlaying()) {
clip.loop(Clip.LOOP_CONTINUOUSLY);
playing = true;
}
}
}
public void playLoop(){
playLoop(true);
}
No error's. The program works. The background sound is played in a loop, but only 0.5 sec of the clip.
Short sounds (shot or jump sound) are played. Everything works in the IDE: short sounds and full background music.
Problem solved! (may not be the best way).
My problem is that I took the method
public static Image uploadImage (String path)
and rewrote part of it for audio.
In the method for images, there is a string for unpacking the JAR.
InputStream fileInputStreamReader = (jar.getInputStream (jar.getEntry (path)));
Next, I wrote the code for audio. It didn't work directly: it was not the same for
InputStream sourceSound = new BufferedInputStream (fileInputStreamReader);
... ...
return sourceSound;
Next step - I added:
InputStream fileInputStreamReader =(jar.getInputStream(jar.getEntry(path)));
byte[] byteArray = new byte[fileInputStreamReader.available()];
fileInputStreamReader.read(byteArray);
InputStream newInputStreamFromArray = new BufferedInputStream(
new ByteArrayInputStream(byteArray));
sourceSound = newInputStreamFromArray;
And it worked! (I thought so). After posting the question here, I started to think that not all inputStream are written in byte[] byteArray.
I made a copy of the byteArray and wrote it to a file "H:/1.wav".
And this is what I saw in the file:
RIFFp[) WAVEfmt D¬ ± dataäZ) ÿ1VÿEÿR¾ÿVëÿH .
.....................................................................................
.....................................................................................
And etс. The data was cut off. There was no content.
Working code for images:
BufferedImage sourceImage = null;
InputStream fileInputStreamReader = jar.getInputStream(jar.getJarEntry(path));
sourceImage = ImageIO.read(fileInputStreamReader);//magic ImageIO.read () !!!!
Likewise does not work for audio:
InputStream fileInputStreamReader =(jar.getInputStream(jar.getEntry(path)));
byte[] byteArray = new byte[fileInputStreamReader.available()];
fileInputStreamReader.read(byteArray);
I guess I didn’t learn Java well =)
So I solved the problem now like this:
InputStream fileInputStreamReader =(jar.getInputStream(jar.getEntry(path)));
byte[] byteArray = new byte[fileInputStreamReader.available()];
int i = 0;
int byteRead;
while ((byteRead = fileInputStreamReader.read()) != -1) {
byteArray[i] = (byte) byteRead;
i++;
}
InputStream newInputStreamFromArray = new BufferedInputStream(new ByteArrayInputStream(byteArray));
Long and short audios are now read from the JAR normally.
If someone knows how to do it better - I will be glad to hear the answer.

Converting images from .bmp to jpeg2000 on java and eclipse error

I have seen some examples here and installed Java Advanced Imaging Image I/O Tools on my computer, because obviously it is a requirement of processing JPEG2000 images.
After install this i am able to import libraries
e.g.
import com.sun.media.imageio.plugins.*;
after importing, i should be able to use constructors or methods of that library but i am getting this error:
"Access restriction: The type 'J2KImageWriteParam' is not API (restriction on required library 'C:\Program Files (x86)\Java\jre1.8.0_77\lib\ext\jai_imageio.jar')"
After a litle bit research, i found out that i can change eclipse preferences and ignore that error.
I went through this way: Preferences -> Java -> Compiler -> Errors / Warnings -> Deprecated and Restricted API. Then i changed errors to warnings. But now i can not use that library efficient, cause eclipse suggest me nothing about that library.
My first question is; if there is a better way to do that? Or maybe another way to use this library efficient in eclipse?
EDIT: I found out it was a complication of 32 and 64 bit versions. After installing 32bit JDK and reference the jai_imageio.jar it worked fine.
And second; Can anybody give a plain example to me about converting .bmp image to jpeg2000 image. That would help a lot to me about undesrtanding the context.
Thank you
You need to have these in your imports:
import javax.imageio.*;
import javax.imageio.stream.*;
import com.sun.media.imageio.plugins.jpeg2000.*;
import com.sun.media.imageio.stream.*;
and these jars
jai_imageio.jar;jai_codec.jar;jai_core.jar
This is an example that runs fine for me - but dont know if the produced j2k are valid or anything - use your j2000 viewer to check that.
public void toJ2000(String inputFile, String outputFile) throws IOException {
J2KImageWriteParam iwp = new J2KImageWriteParam();
FileInputStream fis = new FileInputStream(new File(inputFile));
BufferedImage image = ImageIO.read(fis);
fis.close();
if (image == null)
{
System.out.println("If no registered ImageReader claims to be able to read the resulting stream");
}
Iterator writers = ImageIO.getImageWritersByFormatName("JPEG2000");
String name = null;
ImageWriter writer = null;
while (name != "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriter") {
writer = (ImageWriter) writers.next();
name = writer.getClass().getName();
System.out.println(name);
}
File f = new File(outputFile);
long s = System.currentTimeMillis();
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
J2KImageWriteParam param = (J2KImageWriteParam) writer.getDefaultWriteParam();
IIOImage ioimage = new IIOImage(image, null, null);
writer.write(null, ioimage, param);
System.out.println(System.currentTimeMillis() - s);
writer.dispose();
ios.flush();
ios.close();
image.flush();
}
public static void main(String[] args) {
TR t=new TR();
try {
t.toJ2000("yel.png", "yel.j2k");
}
catch (Exception ex) { ex.printStackTrace(); }
}

Java - Trouble combining more than 2 .wav files

for a project I'm working on, I want to be able to concatenate multiple .wav files.
Through my research I was able to come up with this code:
File sample1 = new File("F:\\Programming\\Resources\\Java_Sound\\trumpet1.wav");
File sample2 = new File("F:\\Programming\\Resources\\Java_Sound\\trumpet2.wav");
File fileOut = new File("F:\\Programming\\Resources\\Java_Sound\\Test.wav");
AudioInputStream audio1 = AudioSystem.getAudioInputStream(sample1);
AudioInputStream audio2 = AudioSystem.getAudioInputStream(sample2);
AudioInputStream audioBuild = new AudioInputStream(new SequenceInputStream(audio1, audio2), audio1.getFormat(), audio1.getFrameLength() + audio2.getFrameLength());
//for(int i = 0; i < 5; i++){
// audioBuild = new AudioInputStream(new SequenceInputStream(audioBuild, audio2), audioBuild.getFormat(), audioBuild.getFrameLength() + audio2.getFrameLength());
//}
AudioSystem.write(audioBuild, AudioFileFormat.Type.WAVE, fileOut);
it works fine for combining two .wav files, however when I uncomment the for loop the produced .wav file only plays audio for the first concatenation. The audio track appears to end early, as wmp's duration bar only goes about 1\5 of the way across the screen.
I've assumed that the problem is with the header in the created .wav file. I've researched many different web pages discussing how a header in constructed, but all of them had slightly different definitions, but all said the header should be in hex. When converting the stream (not the audio stream, a standard FileInputStream) the headers I had were in decimal. Additionally, after the RIFF part, and before the WAVE part, is supposed to be the size of the whole file, not including the first 8 bytes. However some of mine included hyphens. To be honest I have no clue what those mean. Ignoring them however, the size of the test file after uncommenting the code above is still a larger number.
So after researching both how to concatenate multiple audio files, and how to create\manage .wav headers, I still have no clue why the rest of my audio isn't playing, if it even exists. Any help is greatly appreciated. Thanks in advance.
It might be because the input streams cannot be read more than once. Once you read an input stream, it will be at its end and attempt to read further will read no more bytes from that stream.
This should work with a slight modification, keep creating new audio input streams in your loop:
File sample1 = new File("f1.wav");
File sample2 = new File("f2.wav");
File fileOut = new File("combined.wav");
AudioInputStream audio1 = AudioSystem.getAudioInputStream(sample1);
AudioInputStream audio2 = AudioSystem.getAudioInputStream(sample2);
AudioInputStream audioBuild = new AudioInputStream(new SequenceInputStream(audio1, audio2), audio1.getFormat(), audio1.getFrameLength() + audio2.getFrameLength());
for(int i = 0; i < 5; i++)
{
audioBuild = new AudioInputStream(new SequenceInputStream(audioBuild, /* keep creating new input streams */ AudioSystem.getAudioInputStream(sample2)), audioBuild.getFormat(), audioBuild.getFrameLength() + audio2.getFrameLength());
}
AudioSystem.write(audioBuild, AudioFileFormat.Type.WAVE, fileOut);
Also, ensure your audio formats for the files are exactly the same. That is, same sample rate, same channel count, same bits per sample. Otherwise you'll need additional code to do sample conversion.
This is what I used to join any amount of wave files. I looped through a list of the string values for the wave file paths, and each time I join the previous resulting AudioInputStream with the next clip.
List<String> paths;
AudioInputStream clip1 = null;
for (String path : paths)
{
if(clip1 == null)
{
clip1 = AudioSystem.getAudioInputStream(new File(path));
continue;
}
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(path));
AudioInputStream appendedFiles = new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
clip1 = appendedFiles;
}
AudioSystem.write(clip1, AudioFileFormat.Type.WAVE, new File("exported.wav"));

LineUnavailableException for playing mp3 with java

My goal is to play an mp3 file from Java. With every approach that I took, it always fails with a LineUnavailableException.
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new URL("http://localhost:8080/agriserver/facebook/sound/test6.mp3"));
Clip clip = AudioSystem.getClip(info);
clip.open(inputStream);
clip.start();
Failed attempts to fix it:
Use Sun's mp3 plugin.
Use Jlayer 3rd party library
Use Tritonus 3rd party library
Re-encode the mp3 with Sony Sound Forge, Adobe Sound Booth, all no luck
Re-encode the mp3 with different encode rates and sampling rates
Try to use JMF
Use random mp3 from the Internet that plays fine in other applications
Read postings with the same error. None of the postings have an answer that helped resolve the issue.
Here is the exception:
Exception in thread "main" javax.sound.sampled.LineUnavailableException: line with format MPEG1L3 48000.0 Hz, unknown bits per sample, stereo, unknown frame size, 41.666668 frames/second, not supported.
at com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(DirectAudioDevice.java:494)
at com.sun.media.sound.DirectAudioDevice$DirectClip.implOpen(DirectAudioDevice.java:1280)
at com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:107)
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1061)
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1151)
at Demo.playMp3(Demo.java:83)
Apparently, the mp3 has to be read into one stream. That stream has to be read into a second stream to decode it. The below code worked:
// read the file
AudioInputStream rawInput = AudioSystem.getAudioInputStream(new ByteArrayInputStream(data));
// decode mp3
AudioFormat baseFormat = rawInput.getFormat();
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, // Encoding to use
baseFormat.getSampleRate(), // sample rate (same as base format)
16, // sample size in bits (thx to Javazoom)
baseFormat.getChannels(), // # of Channels
baseFormat.getChannels()*2, // Frame Size
baseFormat.getSampleRate(), // Frame Rate
false // Big Endian
);
AudioInputStream decodedInput = AudioSystem.getAudioInputStream(decodedFormat, rawInput);
OK - Let's start by ruling out your MP3 files and your code.
Pick an MP3 file that you have and
play it with any MP3 player.
Download
http://www.javazoom.net/javalayer/sources/jlayer1.0.1.zip
Extract jl1.0.1.jar from zip file
and put in your classpath
Cut and Paste the code at the end of this answer into your dev environment.
compile and run making sure your mp3
file in step 1 is the parameter to
the file. (In my case I had this "C:\\Users\\romain\\Music\\Al DiMeola\\Elegant Gypsy\\01 Flight over Rio Al DiMeola.mp3")
I tested this and it works fine.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
private String filename;
private Player player;
// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try { player.play(); }
catch (Exception e) { System.out.println(e); }
}
}.start();
}
// test client
public static void main(String[] args) {
String filename = args[0];
MP3 mp3 = new MP3(filename);
mp3.play();
}
}

Categories

Resources