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

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 »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »

Price Scanner via MacPrices.net

B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more

Jobs Board

Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.