• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 631
  • Last Modified:

Java MP3 Player... nasty Exceptions!! Help!

In many Java MP3 players, they use the JMF to create a player that will play MP3s.  For a Software Design lab in college, we are writing a  Media Player.

Here is the MP3Player class:

package soundPlayers;

import de.vdheide.mp3.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.media.*;

public class MP3Player implements ControllerListener, Runnable {

      private Player player = null;
      private File mediaFile;
      private SoundPlayerEventHandler eventHandler;
      private Time duration;
      private Timer timer; // for updating via SoundPlayerEventHandler
      private URL fileURL;
      private Thread playThread = null;

      public MP3Player(String mp3FileStr, SoundPlayerEventHandler evtHandler)
                  throws Exception {

            eventHandler = evtHandler;

            MP3File mp3File = null;
            try {
                  mp3File = new MP3File(mp3FileStr);
            } catch (IOException ex) {
                  System.out.println(ex.getMessage());
            }
            if (player == null) {
                  try {
                        File file = new File(mp3File.getPath());
                        MediaLocator mediaLocator = new MediaLocator(file.toURL());
                        player = Manager.createPlayer(mediaLocator);                              // this throws the exception ****
                        player.addControllerListener(this);
                        System.out.println("Realizing...");
                        player.realize();
                        duration = player.getDuration();
                  } catch (MalformedURLException ex) {
                        System.out.println(ex.getMessage());
                  } catch (NoPlayerException ex) {
                        System.out.println(ex.getMessage());
                  } catch (IOException ex) {
                        System.out.println(ex.getMessage());
                  }
            } else {
                  player.start();
                  System.out.println("Playing " + mp3File.getTitle());
            }
            
            timer = new Timer(250, new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        tick();
                  }
            });
      }

      /**
       * Stops the mp3 track specified by the file supplied to the constructor
       *
       * @throws Exception
       */
      public void stop() throws Exception {
            timer.stop();
            player.stop();
            player.close();
            player = null;
      }

      /**
       * Plays the mp3 track specified by the file supplied to the constructor
       *
       * @throws Exception
       *             if an error occurs
       */
      public void play() throws Exception {
            if (player != null) {
                  timer.start();
                  player.start();
            }
      }

      // An internal method that updates the progress bar.
      // The Timer object calls it 10 times a second.
      // If the sound has finished, it resets to the beginning
      private void tick() {
            if (player != null) {
                  Time time = player.getMediaTime();

                  if (eventHandler != null) {
                        double percent = time.getSeconds() / duration.getSeconds();
                        eventHandler.update(percent);
                  }
            } else {
                  eventHandler.update(-1);
            }
      }
      
      public void controllerUpdate(ControllerEvent ev) {
            if(ev instanceof RealizeCompleteEvent) {
                  player.prefetch();
                  System.out.println("Prefetching...");
            }
            if(ev instanceof PrefetchCompleteEvent) {
                  Time time = player.getDuration();
                  playThread = new Thread(this);
                  playThread.start();
                  player.getGainControl().setLevel(1);
                  player.start();
            }
            if(ev instanceof EndOfMediaEvent) {
                  player.removeControllerListener(this);
                  player.stop();
                  player.close();
                  player = null;
                  if(playThread != null) {
                        playThread = null;
                  }
            }
      }
      
      public void run() {

      }

}


However, the following stack is printed when I try to create a player (Manager.createPlayer())

Thread [AWT-EventQueue-0] (Suspended (exception ClassCastException))
      MpegParser(BasicPullParser).setSource(DataSource) line: 69
      MpegParser.setSource(DataSource) line: 250
      BasicSourceModule.createDemultiplexer(DataSource) line: 138
      BasicSourceModule.createModule(DataSource) line: 96
      PlaybackEngine.setSource(DataSource) line: 124
      Handler(MediaPlayer).setSource(DataSource) line: 30
      Manager.createPlayerForSource(DataSource, String, boolean[]) line: 1453
      Manager.createPlayerForContent(MediaLocator, boolean, Hashtable) line: 1326
      Manager.createPlayer(MediaLocator) line: 417
      MP3Player.<init>(String, SoundPlayerEventHandler) line: 46
      MP3Item.play(SoundPlayerEventHandler) line: 85
      MediaPlayerMgr.playMediaItem(MediaItem) line: 74
      MediaPlayerMgr.handlePlay() line: 62
      MediaPlayerUI.actionPerformed(ActionEvent) line: 150
      JButton(AbstractButton).fireActionPerformed(ActionEvent) line: not available
      AbstractButton$Handler.actionPerformed(ActionEvent) line: not available
      DefaultButtonModel.fireActionPerformed(ActionEvent) line: not available
      DefaultButtonModel.setPressed(boolean) line: not available
      BasicButtonListener.mouseReleased(MouseEvent) line: not available
      AWTEventMulticaster.mouseReleased(MouseEvent) line: not available
      JButton(Component).processMouseEvent(MouseEvent) line: not available
      JButton(JComponent).processMouseEvent(MouseEvent) line: not available
      JButton(Component).processEvent(AWTEvent) line: not available
      JButton(Container).processEvent(AWTEvent) line: not available
      JButton(Component).dispatchEventImpl(AWTEvent) line: not available
      JButton(Container).dispatchEventImpl(AWTEvent) line: not available
      JButton(Component).dispatchEvent(AWTEvent) line: not available
      LightweightDispatcher.retargetMouseEvent(Component, int, MouseEvent) line: not available
      LightweightDispatcher.processMouseEvent(MouseEvent) line: not available
      LightweightDispatcher.dispatchEvent(AWTEvent) line: not available
      MediaPlayerUI(Container).dispatchEventImpl(AWTEvent) line: not available
      MediaPlayerUI(Window).dispatchEventImpl(AWTEvent) line: not available
      MediaPlayerUI(Component).dispatchEvent(AWTEvent) line: not available
      EventQueue.dispatchEvent(AWTEvent) line: not available
      EventDispatchThread.pumpOneEventForHierarchy(int, Component) line: not available
      EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: not available
      EventDispatchThread.pumpEvents(int, Conditional) line: not available
      EventDispatchThread.pumpEvents(Conditional) line: not available
      EventDispatchThread.run() line: not available


Just to note, once in a great while, this exception is not thrown at all, but once it's thrown once, it will continue to be thrown for that session.

I am using Eclipse 3.0.1 and Java 5.0 Update 2 for everything; hopefully Java isn't corrupt or something...
Also, the Java MP3 plugin is installed, as well as the latest version of JMF.

Anyway, all of the open source MP3 players I could find throw this exception in the same manner as well.

Thanks!!
0
Cory_Larson04
Asked:
Cory_Larson04
  • 5
  • 4
1 Solution
 
objectsCommented:
I've used the following without problem

http://www.javazoom.net/javalayer/javalayer.html
0
 
Cory_Larson04Author Commented:
Do you have any example code?  I've looked at this and can't really figure out how to use it...

The only code I need to see is how to pass a file to the Player class, since it wants an InputStream.  

Sorry, only my first few months with Java...
0
 
objectsCommented:
Haven't actually used it with JMF.

Have you tried this decoder:

http://java.sun.com/products/java-media/jmf/mp3/download.html
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
Cory_Larson04Author Commented:
objects, I have accepted your answer, since I got an MP3 file to play using JLayer and MP3SPI... But, if you could help me find some example code for stopping/pausing that would be good.  Thanks!
0
 
objectsCommented:
you should need to stop streaming data, how are you streaming the data currently?
0
 
Cory_Larson04Author Commented:
The following is the code from JavaZOOM for playing an MP3 using their MP3SPI, and it works just fine, but supposedly there is a built in Player class somewhere in their library, but I haven't had any luck using or even finding that...  I searched through their jlGUI MP3 player code that's built around their own JLayer and MP3SPI but it's loaded with Controller code or something... the player they use in their code is declared:

private BasicController thePlayer = null;

but, I find no reference anywhere else in their code to this "BasicController".... oh well.


Here's the streaming data code for playing an MP3 right now:

import javax.sound.sampled.*;
import java.io.*;

public class mp3spi {
      
      public static void main(String[] args) {
            
            mp3spi testProgram = new mp3spi();
            
            String mp3String = "D:/Songs/C/Cake - Arco Arena.mp3";
            
            testProgram.testPlay(mp3String);
            
      }

      public void testPlay(String filename) {
            try {
                  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);
                  // Play now.
                  rawplay(decodedFormat, din);
                  in.close();
            } catch (Exception e) {
                  //Handle exception.
            }
      }

      private 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 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;
      }

}
0
 
objectsCommented:
The source for the Player class is available at:
http://www.javazoom.net/jlgui/sources.html
0
 
Cory_Larson04Author Commented:
Yeah, I've looked at the source code...way too many extras to sort out the code I need.  Oh well, thanks for your help, this is just for a personal project I'm going to work on in spare time.

No need to respond... :)
0
 
objectsCommented:
Basically what you need to do is stop/pause the loop in raw play.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now