TweetFollow Us on Twitter

MP3 Player Dashboard Volume Number: 17 (2001)
Issue Number: 3
Column Tag: Multimedia

Putting an MP3 Player in the Dashboard

By Ron Davis

Adding Code To Play MP3 Files Into The PowerPlant Dashboard Example

Introduction

To me, one of the coolest things in programming is when something that someone else wrote works easily. You make one call and something you know took a lot of doing just happens, as advertised. Unfortunately this is a rare thing in the world of the programmer, but in this article you'll see one of those things happen, thanks to the QuickTime team. We'll see how to write an application that plays MP3 files, with an absurdly small amount of code.

One caveat before we start. There is more than one way to play an MP3 file from code on the Mac; this is just one. I recently read a comment in an article in the Game Developer Magazine that is relevant here, "Fast, cheap, good - pick two." This article will show you how to do it fast and cheap. My personal opinion is that in most cases it's still pretty good, but there is a problem with QuickTime playback on cooperative operating systems that causes skipping in some cases. The implementation this article uses will skip, especially when it is in the background and you are doing other things in the front. The good news is that it won't skip under Mac OS X, and we'll be writing a Carbon application.

Starting with the PowerPlant Dashboard

We're going to use Metrowerk's application framework PowerPlant to implement this application. Why PowerPlant? Because I like it and it gives us a starting place. The starting place is the Appearance Stationary. Create a new Project. Click the "Mac OS PowerPlant Stationary" wizard. Tell CodeWarrior where you want to save. When the Stationary window comes up, expand Carbon, and select Appearance. CW will then create a folder on your drive with the Dashboard application in it. Dashboard is a simple application with one window. It is this window we are going to turn into our MP3 player's controller.

Let's start out in Constructor and make our controls. Open the AppResources.ppob file. Double click "Appearance Window". Delete all of the objects in the window. Now add 3 LCmdBevelButtons, "Play", "Stop", "Pause". We're going to use LCmdBevelButtons so we don't have to add listening code to our class. Instead, we can just hook into the Command handling mechanism already in place. When configuring each button, you need to change three fields: the Pane ID, Title, and Command Number. When you get back to the project, you will need to add constants for these commands. Table 1 shows the values I used.

Title   Const   Pane ID   Command Number
Play   cmd_Play   'play'   1000
Stop   cmd_Stop   'stop'   1010
Pause   cmd_Pause   'paus'   1020

Table 1. Constant and command values.


Figure 1. Controller Window in Constructor.

Tin Constructor, the controller window looks like Figure 1. Since we used LCmdBevelButtons, we have to add menu items with the command numbers. Add a new menu in Constructor. Call the menu "Controls." Give it three commands with titles and command numbers just like the buttons. Don't forget to add the menu to the Menu Bar (or it won't show up in your application).

At this point, you can run the application and a window will show up with all of the buttons disabled.

Writing the Code

Now we need to write some code to make our player work. Everything is going to happen in the CAppearanceApp class. We'll handle opening the MP3 file and the Play, Stop and Pause controls from here. In order to do this, we are going to have to add a few routines and instance variables. Open the header for CAppearanceApp. We need to add a variable that holds the FSSpec of the currently playing MP3 file and a QuickTime Movie variable of the currently playing MP3. The standard appearance application doesn't keep track of the window once it creates it, but we need to make sure there is only one window open, since we can only play one MP3 at a time. For this reason, we need to add an instance variable to hold the window. This "one MP3 at a time" limitation is ours, not QuickTime's. You could play multiple sound files at once if you wanted.

QuickTime treats an MP3 just like a movie. As a matter of fact, you could use a movie controller to play the MP3 and you wouldn't need our command buttons. On the other hand, you would lose some level of control and you would have to display something on the screen. Our method will allow us to play an MP3 with only the UI we want, or no UI at all.

There are two other things that need to be added to the class declaration of CAppearanceApp. We'll be writing two new methods, ChooseFile and SetUpMP3. Listing 1 shows the complete CAppearanceApp class.

Listing 1: Declaring our custom class

CAppearanceApp,h

class CAppearanceApp : public LApplication {

public:
                              CAppearanceApp();
   virtual                  ~CAppearanceApp();

   virtual Boolean   ObeyCommand(
                              CommandT         inCommand,
                              void*            ioParam = nil);   

   virtual void         FindCommandStatus(
                              CommandT         inCommand,
                              Boolean&         outEnabled,
                              Boolean&         outUsesMark,
                              UInt16&         outMark,
                           Str255            outName);
   virtual void         ChooseFile();
               void         SetUpMP3( bool startPlaying );
protected:
   virtual void         StartUp();

         void               RegisterClasses();

         LWindow*          mWindow;
         FSSpec            mMP3File;
         Movie               mMovie;

};
CAppearanceApp.cp

CAppearanceApp::CAppearanceApp()
   :mWindow(NULL), mMovie(NULL)
{
   bool cantRun = false;

   // Register ourselves with the Appearance Manager
   if (UEnvironment::HasFeature(env_HasAppearance)) {
      ::RegisterAppearanceClient();
   }

   long result;
   if (::Gestalt(gestaltQuickTime, &result) != noErr ) {
      // put a dialog here that says we need QT
      cantRun = true;
   } else 
   {
      ::Gestalt(gestaltQuickTimeVersion, &result);
      if ( result < 0x0400 )
      {
         cantRun = true;
      }
   }

   if ( cantRun )
   {
      // you should put up an alert here telling the user why.
      ExitToShell();
   }

   RegisterClasses();

   EnterMovies();
}

The first thing we do is initialize our mWindow and mMovie variables to NULL. We are going to check them later to determine if the window or movie has already been created, so they had better be NULL the first time we check it.

We need to check for QuickTime. We do this with the Gestalt calls in the center. I went ahead and checked for QuickTime version as well. If we don't have QuickTime, we exit the program right here. If we do have it, we register our classes and call EnterMovies. EnterMovies is the QuickTime initialization call and must be made before calling any other QuickTime Routines.

Listing 3 contains the new CAppearanceApp::Startup routine. The default behavior of Appearance is to open a new window at start up. But what does New mean in our app? This isn't a recording app; there are no new MP3s to be created. So what we are going to do is stop New from happening at all. While we're at it, we'll make Open happen in its place, which will let us open an MP3 file and play it.

Listing 3: The start-up routine

CAppearanceApp::StartUp
void CAppearanceApp::StartUp()
{
   ObeyCommand(cmd_Open, nil);
}

Now we need to make sure the New menu command isn't even available to the user and that the commands for our controls are enabled. Go to FindCommandStatus and change the cmd_new to cmd_open. Then add cases for the constants we defined for our commands. When it is done, your FindCommandStatus should look like Listing 4.

Listing 4: Adjusting our menu items

CAppearanceApp::FindCommandStatus

void CAppearanceApp::FindCommandStatus(
   CommandT   inCommand,
   Boolean&   outEnabled,
   Boolean&   outUsesMark,
   UInt16&      outMark,
   Str255      outName)
{
   switch (inCommand) {
      case cmd_Open: 
      case cmd_Play:
      case cmd_Stop:
      case cmd_Pause:
      {
         outEnabled = true;
         break;
      }
      default: {
      LApplication::FindCommandStatus(inCommand, outEnabled,
                                 outUsesMark, outMark, outName);
         break;
      }
   }
}

To handle the Open menu command, we need to change a couple of things. As all PowerPlant programmers know, you do the actual work of a menu command in the ObeyCommand method and that is where the code is right now to display the window. We're going to change that a little. We need to pick a file before we open the window, so we're going to create a new method called ChooseFile to handle picking the file and opening the window. Listing 5 contains the complete ChooseFile method.

Listing 5: Choosing a file

CAppearanceApp:: ChooseFile
void CAppearanceApp::ChooseFile()
{
   PP_StandardDialogs::LFileChooser   chooser;
   NavDialogOptions*   options = chooser.GetDialogOptions();
   if (options != nil) {
      options->dialogOptionFlags =   kNavDefaultNavDlogOptions
                              + kNavNoTypePopup
                              + kNavAllowMultipleFiles;
   }
   chooser.SetObjectFilterProc( NavServFileFilterProc );
   if (chooser.AskOpenFile( LFileTypeList(fileTypes_All))) {         // let the filter proc handle types
      chooser.GetFileSpec( 1, mMP3File);
      if ( mWindow == NULL )
      {
      mWindow = LWindow::CreateWindow(PPob_SampleWindow, this);
         ThrowIfNil_(mWindow);
         mWindow->Show();
      }
      SetUpMP3( true );
   }
}

A number of things are happening in this routine. We are using PowerPlant's LFileChooser to handle the open dialog. Under Carbon, this will always use Navigation Services. First we set up Navigation Services options, telling it not to use the types pop-up menu and to only pick one file. (Yes, adding kNavAllowMultipleFiles only lets you pick one file. Go figure.) Then we tell the LFileChooser and Nav Services to use our filter procedure. We'll talk about the filter proc in a minute. After the set up, we do the AskOpenFile, which will handled by putting the dialog up and getting its results. If the user doesn't cancel, it will return true and we will execute the code inside our if.

The first thing we do is get the file system specification of the file the user picked. We assign it to our instance variable for later use. Then we create the window if it doesn't exist. Once the window exists, we call SetUpMP3, which we are going to write next.

Before we go on, Listing 6 shows the Nav Services Filter proc I'm using. It checks to see if the type of the file is one of the two MP3 file types I know about and it also checks to see if the file ends with .mp3 or .MP3, which should catch most MP3 files.

Listing 6: Filter files for the Open dialog box

NavServFileFilterProc
pascal Boolean NavServFileFilterProc (
                        AEDesc* theItemAEDesc, void* info,
                        NavCallBackUserData /*callBackUD*/,
                        NavFilterModes /*filterMode*/ )
{
   OSErr theErr = noErr;
   Boolean display = false;
   NavFileOrFolderInfo* theInfo = (NavFileOrFolderInfo*)info;
   if ( theItemAEDesc->descriptorType == typeFSS )
   {
      if ( theInfo->isFolder ) // show folders and volumes
      {
         return true; 
      }
   }
   StAEDescriptor   aSpecDesc;
   if (::AECoerceDesc(theItemAEDesc, typeFSS, aSpecDesc) == noErr) {
      FSSpec   spec;
   OSErr   err = ::AEGetDescData(aSpecDesc, &spec, sizeof(FSSpec));
      ThrowIfOSErr_(err);
      {
         FInfo   finderInfo;
         ::FSpGetFInfo( &spec, &finderInfo );
         LStr255   tempString( spec.name );
         if tempString.EndsWith( "\p.mp3" ) || 
                                 tempString.EndsWith( "\p.MP3" ) )
         {
            display = true;
         }
         if ( finderInfo.fdType == 'MPG3' || 
                                 finderInfo.fdType == 'MP3 ' )
         {
            display = true;
         }
      }
      
   }
   return display;
}

Loading and Playing the MP3

Now we're ready to load the file and play it. The loading of the file takes place in the method SetUpMP3. Listing 6 contains the complete routine. Playing an MP3 using QuickTime is just like playing a movie. The only difference is we don't have to worry much about where it draws.

void CAppearanceApp::SetUpMP3( bool startPlaying )
{
   // mMP3File has been set with the file we want to play.
   // set it up to play.
   if ( mMovie != NULL )
   {
      DisposeMovie(mMovie);
      mMovie = NULL;
   }
   mWindow->SetDescriptor(mMP3File.name);
   // get the movie from the file
   OSErr   err;
   SInt16   movieRefNum;
   err = ::OpenMovieFile(&mMP3File, &movieRefNum, fsRdPerm);
   ThrowIfOSErr_(err);
   SInt16   actualResID = DoTheRightThing;
   Boolean   wasChanged;
   err = ::NewMovieFromFile(&mMovie, movieRefNum, &actualResID,
                     nil, newMovieActive, &wasChanged);
   ThrowIfOSErr_(err);
   err = ::CloseMovieFile(movieRefNum);
   ThrowIfOSErr_(err);
   // start the file playing
   Rect movieBox;
   ::GetMovieBox (mMovie, &movieBox);
   ::OffsetRect (&movieBox, -movieBox.left, -movieBox.top);
   ::SetMovieBox (mMovie, &movieBox);
   ::SetMovieGWorld (mMovie, mWindow->GetMacPort(), nil);
   ::PrerollMovie( mMovie, 0, ::GetMoviePreferredRate(mMovie) 
   // tried asking for less than the whole movie but it seems to load it all anyway.
   err = ::LoadMovieIntoRam( mMovie, 0, ::GetMovieDuration(mMovie), unkeepInRam);
   if ( startPlaying )
   {
      ObeyCommand( cmd_Play ); 
   }
   
}

Listing 6: SetUpMP3, the routine that loads our MP3.

Our program is only going to play one MP3 at a time, and we will reference that MP3 internally as a QuickTime Movie type. Our reference variable is mMovie, which we initialized to NULL in the constuctor. The first thing we do in our routine is check to see if there is already an existing mMovie. If so, we need to dispose of it properly via QuickTime's DisposeMovie routine.

Now we have a clean slate and the first thing we do is set the title of our window to the name of the file we are going to play. Then we load the movie. We tell QuickTime to OpenMovieFile. If there is a problem opening the file, like it isn't really an MP3, then we throw and get out of the routine.

Next we tell QuickTime to create a new Movie for the file, NewMovieFromFile. This routine takes our mMovie variable, the movieRefNum we got from our open call, the actualResID, flags that tell it we want the movie active, and a flag telling us if they had to change any references we gave them. Notice we set actualResID to the name of a Spike Lee movie. This variable is the resource ID of the first resource in our movie file. We set it to DoTheRightThing, in a vain attempt to get Spike's movie, but we won't and QuickTime will set our variable to the actual resource ID, or in our MP3 case, nothing.

Now we have got the movie in QuickTime and we can close the file. Before we can play the file we need to set up its "Movie Box," which is where we want it to play. We do this by getting the current box, making it nothing and assigning the GWorld to our window. None of this really matters to us, but it does to QuickTime.

We do a couple of things to try and minimize skipping. First we preroll the movie. This causes the beginning of the movie to be buffered. If you were opening a stream, you'd have to call PrePreRollMovie. Then we try and load all of the movie into RAM. If this succeeds we'll eliminate skipping. The last parameter of the call is set to unkeepInRam, which is a constant that will allow the memory to be purged if it is needed. You can set it to keepInRam, which won't allow the memory to be freed. I did this and it sucked up a huge amount of RAM and brought my MP3 player to a screeching halt. Remember most MP3s are rather big. I've got the Rush 2112 track I ripped, which is 21 minutes long and 19 Meg on disk. So loading isn't always practical. Of course, given OS X's different memory model, loading probably works well.

Before we leave the routine, we check its parameter and if it is true we give the command to play, which will start the file playing.

The last routine we need to write is the ObeyCommand method. This is a standard PowerPlant method that handles menu commands and will handle our buttons. It is in Listing 7.

Boolean CAppearanceApp::ObeyCommand(
   CommandT   inCommand,
   void*      ioParam)
{
   Boolean      cmdHandled = true;   // Assume we'll handle the command
   switch (inCommand) {
      case cmd_Open: 
      {
         ChooseFile();
      }
      break;
      case cmd_Play:
      {
         ::StartMovie( mMovie );
      }
      break;
      case cmd_Stop:
      {
         ::StopMovie( mMovie );
         ::SetMovieTimeValue( mMovie, 0 );
      }
      break;
      case cmd_Pause:
      {
         ::StopMovie( mMovie );
      }
      break;
      default: {
         cmdHandled = LApplication::ObeyCommand(inCommand, ioParam);
         break;
      }
   }
   return cmdHandled;
}

Listing 7: Obeying commands for the player.

The first command we handle is the open command, which just calls our ChooseFile() method. Next we handle the Play command. To start our already loaded movie playing, we just call QuickTime's StartMovie with our mMovie as the parameter. To Pause the movie, we call StopMovie. StopMovie doesn't move where the "playhead" is for the movie, so if you call StartMovie again it will start playing were it was. The proper behavior for a stop button is to go back to the beginning of the song. So to handle the Stop command, we stop the movie and then move the play position back to the beginning, using SetMovieTimeValue. You could use SetMovieTimeValue to set the play head whereever you wanted in the song. You could even hook it up to a slider and let the user do it. I'll leave that as an exercise for the readers.

Conclusion

That is the basics of playing an MP3 file using QuickTime. If you want to learn more you need to check out the QuickTime API web site, and maybe subscribe to the QuickTime API mailing list.

Biblography


Ron Davis is a consulting Engineer in Apple's iServices group. He's also the author of his own more complete MP3 player, MP3 Hit List, which is soon to be released.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.