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

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.