[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2005-05-12
9
Medium Priority
?
628 Views
Last Modified: 2012-06-27
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
Comment
Question by:Cory_Larson04
  • 5
  • 4
9 Comments
 
LVL 92

Accepted Solution

by:
objects earned 1000 total points
ID: 13991737
I've used the following without problem

http://www.javazoom.net/javalayer/javalayer.html
0
 

Author Comment

by:Cory_Larson04
ID: 13997241
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
 
LVL 92

Expert Comment

by:objects
ID: 14000907
Haven't actually used it with JMF.

Have you tried this decoder:

http://java.sun.com/products/java-media/jmf/mp3/download.html
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:Cory_Larson04
ID: 14016454
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
 
LVL 92

Expert Comment

by:objects
ID: 14016696
you should need to stop streaming data, how are you streaming the data currently?
0
 

Author Comment

by:Cory_Larson04
ID: 14020398
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
 
LVL 92

Expert Comment

by:objects
ID: 14023342
The source for the Player class is available at:
http://www.javazoom.net/jlgui/sources.html
0
 

Author Comment

by:Cory_Larson04
ID: 14024361
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
 
LVL 92

Expert Comment

by:objects
ID: 14024391
Basically what you need to do is stop/pause the loop in raw play.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month18 days, 1 hour left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question