Media Playback Programmatically


#1

I try to create media playback programmatically, but the movie player only show dark screen.
My goal is separate view and controller for mvc pattern and create it without IB.

Here is my codes:

MediaPlayerAppDelegate.h

[code]#import <UIKit/UIKit.h>

@interface MediaPlayerAppDelegate : NSObject

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end[/code]

MediaPlayerAppDelegate.m

[code]#import “MediaPlayerAppDelegate.h”
#import “MediaPlayerViewController.h”

@implementation MediaPlayerAppDelegate

@synthesize window = _window;

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    // Override point for customization after application launch.

    MediaPlayerViewController *mediaPlayerViewController = [[MediaPlayerViewController alloc] init];
    [[self window] setRootViewController:mediaPlayerViewController];

    [mediaPlayerViewController release];

    [self.window makeKeyAndVisible];
    return YES;
    }

  • (void)applicationWillResignActive:(UIApplication )application
    {
    /

    Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    */
    }

  • (void)applicationDidEnterBackground:(UIApplication )application
    {
    /

    Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    */
    }

  • (void)applicationWillEnterForeground:(UIApplication )application
    {
    /

    Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    */
    }

  • (void)applicationDidBecomeActive:(UIApplication )application
    {
    /

    Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    */
    }

  • (void)applicationWillTerminate:(UIApplication )application
    {
    /

    Called when the application is about to terminate.
    Save data if appropriate.
    See also applicationDidEnterBackground:.
    */
    }

  • (void)dealloc
    {
    [_window release];
    [super dealloc];
    }

@end[/code]

MediaPlayerView.h

[code]#import <UIKit/UIKit.h>

@class MediaPlayerViewController;

@interface MediaPlayerView : UIView {
MediaPlayerViewController *_viewController;
}

@property (nonatomic, retain) MediaPlayerViewController *viewController;

  • (void)centerButton:(UIButton *)button;

@end[/code]

MediaPlayerView.m

[code]#import “MediaPlayerView.h”
#import “MediaPlayerViewController.h”

@implementation MediaPlayerView

@synthesize viewController = _viewController;

  • (id)initWithFrame:(CGRect)frame
    {
    self = [super initWithFrame:frame];
    if (self) {
    // Initialization code

      UIButton *audioFileButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      UIButton *shortSoundButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      
      [audioFileButton setFrame:CGRectMake(0, 40, 150, 40)];
      [shortSoundButton setFrame:CGRectMake(0, 100, 200, 40)];
      
      [self centerButton:audioFileButton];
      [self centerButton:shortSoundButton];
      
      [audioFileButton setTitle:@"Play Audio File" forState:UIControlStateNormal];
      [shortSoundButton setTitle:@"Play Short Sound" forState:UIControlStateNormal];
      
      _viewController = [[MediaPlayerViewController alloc] init];
      [audioFileButton addTarget:[self viewController] action:@selector(playAudioFile:) 
                forControlEvents:UIControlEventTouchUpInside];
      [shortSoundButton addTarget:[self viewController] action:@selector(playShortSound:) 
                 forControlEvents:UIControlEventTouchUpInside];
      
      [self addSubview:audioFileButton];
      [self addSubview:shortSoundButton];
    

    }
    return self;
    }

  • (void)centerButton:(UIButton *)button {
    CGRect originalSize = [button frame];
    int xCoordinate = [[UIScreen mainScreen] bounds].size.width/2.0;

    xCoordinate = xCoordinate - originalSize.size.width/2;

    [button setFrame:CGRectMake(xCoordinate, originalSize.origin.y, originalSize.size.width, originalSize.size.height)];
    }

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

  • (void)drawRect:(CGRect)rect
    {
    // Drawing code
    }
    */

  • (void)dealloc {
    [_viewController release];
    [super dealloc];
    }

@end[/code]

MediaPlayerViewController.h

[code]#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface MediaPlayerViewController : UIViewController {
SystemSoundID shortSound;
AVAudioPlayer *_audioPlayer;
MPMoviePlayerController *_moviePlayer;

UIButton *audioFileButton;

}

@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
@property (nonatomic, retain) MPMoviePlayerController *moviePlayer;

  • (void)playAudioFile:(id)sender;
  • (void)playShortSound:(id)sender;

@end[/code]

MediaPlayerViewController.m

[code]#import “MediaPlayerViewController.h”
#import “MediaPlayerView.h”

@implementation MediaPlayerViewController

@synthesize audioPlayer = _audioPlayer, moviePlayer = _moviePlayer;

  • (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization

      // ====== Short Audio =======
      NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12" ofType:@"aif"];
      
      if (soundPath) {
          NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
          
          OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL, &shortSound);
          if (err != kAudioServicesNoError) {
              NSLog(@"Could not load %@, error code: %ld", soundURL, err);
          }
      }
      
      // ======= Sound File =======
      NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"Music" ofType:@"mp3"];
      
      if (musicPath) {
          NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
          _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
          [[self audioPlayer] setDelegate:self];
      }
      
      // ======= Movie Player ======
      NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"Layers" ofType:@"m4v"];
      
      if (moviePath) {
          NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
          _moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL];
      }
    

    }
    return self;
    }

  • (void)playAudioFile:(id)sender {
    audioFileButton = sender;
    if ([[self audioPlayer] isPlaying]) {
    [[self audioPlayer] stop];
    [sender setTitle:@“Play Audio File” forState:UIControlStateNormal];
    } else {
    [[self audioPlayer] play];
    [sender setTitle:@“Stop Audio File” forState:UIControlStateNormal];
    }
    }

  • (void)playShortSound:(id)sender {
    AudioServicesPlaySystemSound(shortSound);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }

  • (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [audioFileButton setTitle:@“Play Audio File” forState:UIControlStateNormal];
    }

  • (void)didReceiveMemoryWarning
    {
    // Releases the view if it doesn’t have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren’t in use.
    }

#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.

  • (void)loadView {
    MediaPlayerView *mPlayer = [[MediaPlayerView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [mPlayer setBackgroundColor:[UIColor clearColor]];
    [self setView:mPlayer];
    [mPlayer release];
    }

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    float halfHeight = [[self view] bounds].size.height / 2.0;
    float width = [[self view] bounds].size.width;

    [[[self moviePlayer] view] setFrame:CGRectMake(0, halfHeight, width, halfHeight)];
    [[self view] addSubview:[[self moviePlayer] view]];
    }

  • (void)viewDidUnload
    {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    }

  • (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }

@end[/code]