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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply 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
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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.