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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
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
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.