Many applications on a mobile device need audio and video playback. In this chapter, you will learn how to use the most common audio and video playback routines the iOS SDK offers. In addition, we will look at background processes and multitasking.
Create an iPhone Window-based Application in Xcode. Name this project MediaPlayer.
MediaPlayer will have a very simple interface so that you can concentrate on the guts of media playback. The application will display two buttons that will initiate different types of audio playback, and it will also display a movie. The object diagram for this application is shown in Figure 27.1.
Create a new UIViewController subclass ( → → ) and check With XIB for user interface. Name this subclass MediaPlayerViewController. In MediaPlayerAppDelegate.m, import the header file for MediaPlayerViewController, create an instance of the view controller, and set it to be the window’s rootViewController.
#import "MediaPlayerAppDelegate.h" #import "MediaPlayerViewController.h" @implementation MediaPlayerAppDelegate @synthesize window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MediaPlayerViewController *vc = [[MediaPlayerViewController alloc] init]; [[self window] setRootViewController:vc]; [vc release]; [[self window] makeKeyAndVisible]; return YES; }
The application needs two buttons for playing audio. One button’s title will change during runtime, and both buttons need action methods. In MediaPlayerViewController.h, declare an instance variable for the button with the title that will change and the two action methods.
@interface MediaPlayerViewController : UIViewController { IBOutlet UIButton *audioButton; } - (IBAction)playAudioFile:(id)sender; - (IBAction)playShortSound:(id)sender; @end
Save this file and then open MediaPlayerViewController.xib.
Click the View object in the outline view to open it. Drag two UIButton objects onto the view and title them as shown in Figure 27.3. Then, make the action connections from the buttons back to the MediaPlayerViewController. Finally, connect the audioButton outlet to the button labeled Play Audio File.
In order to build and run the application without warnings, you will need stub methods for the IBActions you declared. In MediaPlayerViewController.m, implement them as follows.
- (IBAction)playAudioFile:(id)sender { NSLog(@"playAudioFile!"); } - (IBAction)playShortSound:(id)sender { NSLog(@"playSound!"); }
If you want to check your connections, you can build and run the application. The log messages should show up on the console.
3.137.212.124