Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Playing an MP3

807607Oct 6 2006 — edited Oct 6 2006
Hi folks

I'm having some trouble with my code for playing an mp3 file. This used to be working but now I've ported it over to another computer and it's not working. Maybe I'm missing a resource or maybe there's something wrong with my code.

Advice anyone?

here's the exception:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at tjacobs.mp3.MP3.play(MP3.java:113)
at tjacobs.mp3.MP3.main(MP3.java:173)

And here's my code:
/*
 * Created on Jun 29, 2005 by @author Tom Jacobs
 *
 */
package tjacobs.mp3;
import javax.sound.midi.MetaEventListener;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.sampled.*;
import javax.swing.JFileChooser;

import java.io.*;
import java.lang.reflect.Type;

/**
 * Call play() with the file name of an MP3 and it will play that MP3
 */
public class MP3 {

	private MP3() {
		super();
	}
	
	private static class MP3Runnable implements Runnable {
		String file;
		MP3Runnable(String filename) {
			file = filename;
		}
		
		public void run() {
			play(file);
		}
	}
	
	public static void play(String filename, boolean createThread) {
		if (!createThread) {
			play(filename);
		}
		else {
			Runnable r = new MP3Runnable(filename);
			Thread t = new Thread(r);
			t.start();
		}
	}
	
	public static void play(InputStream stream) {
		try {   
			AudioInputStream in= AudioSystem.getAudioInputStream(stream);
		    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);
		    // Play now. 
		    rawplay(decodedFormat, din);
		    in.close();
		} 
		//catch(RuntimeException re) {}
		catch (UnsupportedAudioFileException ex) {
			ex.printStackTrace();
		}
		catch (IOException iox) {
			iox.printStackTrace();
		}
		catch (LineUnavailableException lue) {
			lue.printStackTrace();
		}
	}

	public static void play(String filename)
	{
	    File file = new File(filename);
	    play(file);
	}
		
	
	public static void play(File audiofile) {
		try {
			if (audiofile.getName().endsWith(".mid") || audiofile.getName().endsWith(".midi")) {
				Sequence sequence = MidiSystem.getSequence(audiofile );
				if (sequence != null) {
					//				 These methods may throw MidiUnavailableException
					try {
						final Sequencer sequencer = MidiSystem.getSequencer();
						sequencer.open();
						sequencer.setSequence(sequence);
						sequencer.start();
						MetaEventListener listener = new MetaEventListener() {
							public void meta(MetaMessage ev) {
								if ( ev.getType() == 47 ) { // end of stream
									//						     sequencer.stop();
									//						     sequencer.close();
									//						     System.exit( 0 );
								}
							}
						};
					} catch (MidiUnavailableException ex) {
						//nothing we can do
						return;
					}

				}
				return;
			}
			AudioInputStream in= AudioSystem.getAudioInputStream(audiofile);
			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);
			// Play now. 
			rawplay(decodedFormat, din);
			in.close();
		} catch (Exception e)
		{
			e.printStackTrace();
			//Handle exception.
		}
	} 

	private static void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException,                                                                                                LineUnavailableException
	{
		byte[] data = new byte[4096];
		SourceDataLine line = getLine(targetFormat); 
		if (line != null)
		{
			// Start
			line.start();
			int nBytesRead = 0, nBytesWritten = 0;
			while (nBytesRead != -1)
			{
				nBytesRead = din.read(data, 0, data.length);
				if (nBytesRead != -1) nBytesWritten = line.write(data, 0, nBytesRead);
			}
			// Stop
			line.drain();
			line.stop();
			line.close();
			din.close();
		} 
	}

	private static SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException
	{
	  SourceDataLine res = null;
	  DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
	  res = (SourceDataLine) AudioSystem.getLine(info);
	  res.open(audioFormat);
	  return res;
	}
	
	public static  void main (String args[]) {
		JFileChooser chooser = new JFileChooser();
		File f = new File("C:/program files/englishotto/media/music");
		chooser.setCurrentDirectory(f);
		int result = chooser.showOpenDialog(null);
		if (result == chooser.APPROVE_OPTION) {
			File mp3 = chooser.getSelectedFile();
//			try {
				play(mp3);
				//FileInputStream fis = new FileInputStream(mp3);
				//PushbackInputStream bis = new PushbackInputStream(fis);
				//BufferedInputStream bis = new BufferedInputStream(fis);
				//play(bis);
//			}
//			catch (FileNotFoundException ex) {
//				ex.printStackTrace();
//			}
		}
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 3 2006
Added on Oct 6 2006
4 comments
221 views