Home > Articles > Programming > Mac and iOS Programming

  • Print
  • + Share This
This chapter is from the book

Your First Core Audio Application

Now let’s get a feel for Core Audio code by actually writing some. The audio engine APIs have a lot of moving parts and are, therefore, more complex, so we’ll make trivial use of one of the helper APIs. In this first example, we’ll get some metadata (information about the audio) from an audio file.

Launch Xcode, go to File > New Project, select the Mac OS X Application templates, and choose the Command Line Tool template; select the Foundation type in the pop-up menu below the template icon. When prompted, call the project CAMetadata. The resulting project has one user-editable source file, main.m, and produces an executable called CAMetadata, which you can run from Xcode or in the Terminal.

Select the CAMetadata.m file. You’ll see that it has a single main() function that sets up an NSAutoReleasePool, prints a “Hello, World!” log message, and drains the pool before terminating. Replace the comment and the printf so that main() looks like Listing 1.1. We’ve added numbered comments to the ends of some of the statements as callouts so that we can explain what this code does, line by line.

Listing 1.1 Your First Core Audio Application

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    if (argc < 2) {
        printf ("Usage: CAMetadata /full/path/to/audiofile\n");
        return -1;
    }                                                             // 1

NSString *audioFilePath = [[NSString stringWithUTF8String:argv[1]]
                            stringByExpandingTildeInPath];        // 2
    NSURL *audioURL = [NSURL fileURLWithPath:audioFilePath];      // 3
    AudioFileID audioFile;                                        // 4
    OSStatus theErr = noErr;                                      // 5
    theErr = AudioFileOpenURL((CFURLRef)audioURL,
                              kAudioFileReadPermission,
                              0,
                              &audioFile);                        // 6
    assert (theErr == noErr);                                     // 7
    UInt32 dictionarySize = 0;                                    // 8
    theErr = AudioFileGetPropertyInfo (audioFile,
                                       kAudioFilePropertyInfoDictionary,
                                       &dictionarySize,
                                       0);                        // 9
    assert (theErr == noErr);                                     // 10
    CFDictionaryRef dictionary;                                   // 11
    theErr = AudioFileGetProperty (audioFile,
                                   kAudioFilePropertyInfoDictionary,
                                   &dictionarySize,
                                   &dictionary);                  // 12
    assert (theErr == noErr);                                     // 13
    NSLog (@"dictionary: %@", dictionary);                        // 14
    CFRelease (dictionary);                                       // 15
    theErr = AudioFileClose (audioFile);                          // 16
    assert (theErr == noErr);                                     // 17

     [pool drain];
     return 0;
}

Now let’s walk through the code from Listing 1.1:

  1. As in any C program, the main() method accepts a count of arguments (argc) and an array of plain C-string arguments. The first string is the executable name, so you must look to see if there’s a second argument that provides the path to an audio file. If there isn’t, you print a message and terminate.
  2. If there’s a path, you need to convert it from a plain C string to the NSString/CFStringRef representation that Apple’s various frameworks use. Specifying the UTF-8 encoding for this conversion lets you pass in paths that use non-Western characters, in case (like us) you listen to music from all over the world. By using stringByExpandingTildeInPath, you accept the tilde character as a shortcut to the user’s home directory, as in ~/Music/....
  3. The Audio File APIs work with URL representations of file paths, so you must convert the file path to an NSURL.
  4. Core Audio uses the AudioFileID type to refer to audio file objects, so you declare a reference as a local variable.
  5. Most Core Audio functions signal success or failure through their return value, which is of type OSStatus. Any status other than noErr (which is 0) signals an error. You need to check this return value on every Core Audio call because an error early on usually makes subsequent calls meaningless. For example, if you can’t create the AudioFileID object, trying to get properties from the file that object was supposed to represent will always fail. In this example, we’ve used an assert() to terminate the program instantly if we ever get an error, in callouts 7, 10, 13, and 17. Of course, your application will probably want to handle errors with somewhat less brutality.
  6. Here’s the first Core Audio function call: AudioFileOpenURL. It takes four parameters, a CFURLRef, a file permissions flag, a file type hint, and a pointer to receive the created AudioFileID object. You do a toll-free cast of the NSURL to a CFURLRef to match the first parameter’s defined type. For the file permissions, you pass a constant to indicate read permission. You don’t have a hint to provide, so you pass 0 to make Core Audio figure it out for itself. Finally, you use the & (“address of”) operator to provide a pointer to receive the AudioFileID object that gets created.
  7. If AudioFileOpenURL returned an error, die.
  8. To get the file’s metadata, you will be asking for a metadata property, kAudioFilePropertyInfoDictionary. But that call requires allocating memory for the returned metadata in advance. So here, we declare a local variable to receive the size we’ll need to allocate.
  9. To get the needed size, call AudioFileGetPropertyInfo, passing in the AudioFileID, the property you want information about, a pointer to receive the result, and a pointer to a flag variable that indicates whether the property is writeable (because we don’t care, we pass in 0).
  10. If AudioFileGetPropertyInfo failed, terminate.
  11. The call to get a property from an audio file populates different types, based on the property itself. Some properties are numeric; some are strings. The documentation and the Core Audio header files describe these values. Asking for kAudioFilePropertyInfoDictionary results in a dictionary, so we set up a local variable instance of type CFDictionaryRef (which can be cast to an NSDictionary if needed).
  12. You’re finally ready to request the property. Call AudioFileGetProperty, passing in the AudioFileID, the property constant, a pointer to the size you’re prepared to accept (set up in callouts 8–10 with the AudioFileGetPropertyInfo call) and a pointer to receive the value (set up on the previous line).
  13. Again, check the return value and fail if it’s anything other than noErr.
  14. Let’s see what you got. As in any Core Foundation or Cocoa object, you can use "%@" in a format string to get a string representation of the dictionary.
  15. Core Foundation doesn’t offer autorelease, so the CFDictionaryRef received in callout 12 has a retain count of 1. CFRelease() releases your interest in the object.
  16. The AudioFileID also needs to be cleaned up but isn’t a Core Foundation object, per se; therefore, it doesn’t get CFRelease()’d. Instead, it has its own end-of-life function: AudioFileClose().
  17. AudioFileClose() is another Core Audio call, so you should continue to check return codes, though it’s arguably meaningless here because you’re two lines away from terminating anyway.

So that’s about 30 lines of code, but functionally, it’s all about setting up three calls: opening a file, allocating a buffer for the metadata, and getting the metadata.

Running the Example

That was probably more code than you’re used to writing for simple functionality, but it’s done now. Let’s try it out. Click build; you get compile errors. Upon inspection, you should see that all the Core Audio functions and constants aren’t being found.

This is because Core Audio isn’t included by default in Xcode’s command-line executable project, which imports only the Foundation framework. Add a second #import line:

#import <AudioToolbox/AudioToolbox.h>

Audio Toolbox is an “umbrella” header file that includes most of the Core Audio functionality you’ll use in your apps, which means you’ll be importing it into pretty much all the examples. You also need to add the framework to your project. Click the project icon in Xcode’s file navigator, select the CAMetadata target, and click the Build Phases tab. Expand the Link Binaries with Libraries section and click the + button to add a new library to be linked at build time. In the sheet that slides out, select the AudioToolbox.framework, as shown in Figure 1.1.

01fig01.jpg

Figure 1.1 Adding the AudioToolbox.framework to an Xcode project

Now you should be able to build the application without any errors. To run it, you need to provide a path as a command-line argument. You can either open the Terminal and navigate to the project’s build directory or supply an argument with Xcode. Let’s do the latter:

  • From the Scheme pop-up menu, select Edit Scheme.
  • Select the Run CAMetadata item and click the Arguments tab.
  • Press + to add an argument and supply the path to an audio file on your hard drive.
  • If your path has spaces in it, use quotation marks. For example, we’re using an MP3 bought online, located at ~/Music/iTunes/iTunes Music/Amazon MP3/Metric/Fantasies/05 - Gold Guns Girls.mp3. Click OK to dismiss the Scheme Editor sheet.
  • Bring up Xcode’s Console pane with Shift-image-C and click Run.

Assuming that your path is valid, your output will look something like this:

2010-02-18 09:43:17.623 CAMetadata[17104:a0f] dictionary: {

    album = Fantasies;
    "approximate duration in seconds" = "245.368";
    artist = Metric;
    comments = "Amazon.com Song ID: 210266948";
    copyright = "2009 Metric Productions";
    genre = "Alternative Rock";
    title = "Gold Guns Girls";
    "track number" = "5/10";
    year = 2009;
}

Well, that’s pretty cool: You’ve got a nice dump of a lot of the same metadata that you’d see in an application such as iTunes. Now let’s check it out with an AAC song from the iTunes Store. Changing the command-line argument to something like ~/Music/iTunes/iTunes Music/Arcade Fire/Funeral/07 Wake Up.m4a gets you the following:

2010-02-18 09:48:15.421 CAMetadata[17665:a0f] dictionary: {
    "approximate duration in seconds" = "335.333";
}

Whoa! What happened to the metadata call?

Nothing, really: Nothing in the documentation promises what you can expect in the info dictionary. As it turns out, Core Audio offers richer support for ID3 tags in .mp3 files than the iTunes tagging found in .m4a files.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020