How to write Java AudioInputStream to MP3? - java

Now I have an AudioInputStream, using the following code I can write it to a WAVE file. While what I want is an MP3 file, what should I do?
AudioInputStream ais= new AudioInputStream(bais1, audioFormat, bufferSize);
try {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("demoFile.wav")
);
}
catch(Exception e) {
e.printStackTrace();
}
In my project, the cache is not big enough to store big files, which means solution like using a tool to convert WAVE to MP3 is not allowed(WAVE file is too big).

Here is a github library of java audio utilities that include claims of being able to encode mp3.
pududits.soundlibs
I haven't used the mp3 libraries, only ogg/vorbis decoding. I'd be tempted to try the JOrbis encoder for ogg/vorbis before getting into mp3's.

Related

How to read mp3 file to a byte array in Java?

I want to read the content of the .mp3 file into a byte array(Not including header and metadata). For this purpose I'm using following code.
File myFile = new File("C:\\Users\\Kaushal28\\Desktop\\a.mp3");
byte[] samples;
AudioInputStream is = AudioSystem.getAudioInputStream(myFile);
DataInputStream dis = new DataInputStream(is); //So we can use readFully()
try{
AudioFormat format = is.getFormat();
samples = new byte[(int)(is.getFrameLength() * format.getFrameSize())];
dis.readFully(samples);
}
finally{
dis.close();
}
Here is the link where it is posted: Here.
I executed this code with a mp3 file of a song. but got following exception:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
I've also tried this with .au file type, but got same exception.
For this I searched on Internet and found this: This SO link.
It says that all wav formats are not supported by java. Is it also true for .mp3 file formats? Or any other reasons due to which I'm getting this exception?

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.

Playing audio in java using Sun.audio

I want just to perform a simple task. (I'm a java newbie). I want to play an audio clip when a button is clicked.
here's the part of my code(which I did exactly by copying a tutorial from Youtube.)
private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {
InputStream in;
try{
in=new FileInputStream(new File("C:\\Users\\Matt\\Documents\\dong.wav"));
AudioStream timeupsound=new AudioStream(in);
AudioPlayer.player.start(timeupsound);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
But the problem is, this doesn't work.
It throws and IOException saying: "could not create audio stream from input stream".
My question is, what am I doing wrong? (as I clearly saw this code work in that youtube video, and I've used the same code. Please help. and once again, I'm a newbie);
The sun package classes should be causing some informative warnings at compile time. Heed them. Don't use classes in that package hierarchy. They are undocumented, are not guaranteed from one Java version to the next, and will probably not be available in a non-Oracle JRE at all.
Instead use the Java Sound based Clip to play audio. See the info. page for working examples.
Note
It might be the WAV is encoded in a format that Java Sound does not support. Media formats are typically 'container formats' that might be encoded using any number of different Codecs. It is likely that WAV is using a more compressive Codec such as MP3 or OGG internally.
I don't know of a Service Provider Interface for the OGG format, but if they are encoded as MP3, you might be able to get it working using the MP3 SPI. See the info. page linked above for details.
Tip
Also change code of the form:
catch (Exception e) { ..
To
catch (Exception e) {
e.printStackTrace(); // very informative! ...

Including all libraries, audio, etc. of a Java program in one JAR file

I am using Netbeans and I am trying to figure out how I can put all of my libraries, music, images, etc. in one JAR file for distribution. I think I have the libraries figured out, but the audio, images, and other such files are giving me trouble.
In my current project I have an audio file that I want to embed in the JAR file too. First I tried one-jar but after a couple of hours I gave up on it. I put the audio file into the JAR file just fine, but I cannot access it from my program. I know I need to use getResourceAsStream as suggested here but I am unclear what I do after I get the input stream. The only way I can see to make it work is to use use the InputStream and create a whole new file (seen below... and it works), but creating a new file seems like a waste (and I don't want people to see an audio file appear when my program is running). Is there no way to directly access the audio file while it is still contained in the .JAR file?
File file = new File("myAudio.wav");
InputStream stream = mypackage.MyApp.class.getResourceAsStream("audio/myAudio.wav");
try {
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
}
EDIT:
The internal structure of my JAR file Contains 1.) a library package (Jama), 2.) my package which is the direct parent of my class files and a folder called "audio" which contains myAudio.wav, and 3.) a META-INF folder which contains my manifest.mf.
EDIT
Audio stream is read something like this. I have tried to use the InputStream directly but I have not had success. I want to point out again that I already have it when I create a new audio file from the input stream of the audio file contained JAR file, but like I said before, it seems like a waste to create a big audio file every time a program is run when the file already exists in the JAR. This file recreation is what I am trying to avoid.
AudioInputStream stream;
Clip music;
try {
stream = AudioSystem.getAudioInputStream(file);
} catch (IOException e) {
} catch (UnsupportedAudioFileException e) {
}
try {
music = AudioSystem.getClip();
} catch (LineUnavailableException e) {
}
try {
start();
} catch (Exception e) {
}
public void start() throws Exception {
music.open((AudioInputStream) stream);
music.start();
music.loop(Clip.LOOP_CONTINUOUSLY);
}
Doesn't AudioSystem.getAudioInputStream(stream); work for you?

Java Media Framework: extract audio info from mp3 file

I'm analyzing music mp3 files. What I'm doing is extracting the audio data from the file and computing music similarity.
I've been using javazoom in order to handle mp3 files. By using audioFormat I'm extracting the raw data from the mp3 file:
byte[] audioBytes = new byte[numBytes];
in_format_init = AudioSystem.getAudioInputStream(musicFile);
AudioFormat formatInit = in_format_init.getFormat();
AudioFormat formatFinal = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
formatInit.getSampleRate(),
16,
formatInit.getChannels(),
formatInit.getChannels()*2,
formatInit.getSampleRate(),
false);
AudioInputStream streamIn = AudioSystem.getAudioInputStream(formatFinal, in_format_init);
while (((numBytesRead = streamIn.read(audioBytes)) != -1))
{...}
By doing this I store the audio data (without headers or tags) in audioBytes and then the info stored in the array is processed.
My question is: is it posible to extract the audio information from an mp3 audio file and store it as I do it in my example? I've been reading about JMF, but it's confusing for me.
Thanks.
I've just had a quick look at the JMF API so I'm not a 100% sure this will be correct or even work at all, but try something like this:
try {
File f = new File ("/path/to/my/audio.mp3");
DataSource ds = Manager.createDataSource(f.toURI().toURL());
ds.connect();
ds.start();
...
} catch (java.io.IOException e) {
...
} catch (NoDataSourceException e) {
...
}
After this try getting the controls from the DataSource: ds.getControls(), and see if any of the controls allows you to read the raw audio data.
You'll probably have to do all kinds of cleanup as well, e.g. ds.disconnect(), after you're done reading the audio.
Also, don't forget to install the JMF MP3 plugin
-- Lauri

Categories

Resources