FirstApp,iphone开发学习总结12,播放音乐、视频

添加AVFoundation.framework 和MediaPlayer.framework。

在NavView.h文件中,添加:

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface NavView1 : UIViewController<AVAudioPlayerDelegate>{
    AVAudioPlayer *audioPlayer;
    MPMoviePlayerController *moviePlayer;
}
@end

 在init中添加音乐url:

- (id)init {
    self = [super init];
    if (self) {
        //...
        NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"yu" ofType:@"mp3"];
        if (musicPath) {
            NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
            audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
            [audioPlayer setDelegate:self];
        }
    }
    return self;
}

 在view中添加2个按钮:

- (void)viewDidLoad
{
    //...
    UIButton *musicPlayBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    musicPlayBtn.frame = CGRectMake(40.070.0240.030.0);
    [musicPlayBtn setTitle:@"Play Music" forState:UIControlStateNormal];
    [musicPlayBtn addTarget:self action:@selector(playMusic:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *movePlayBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    movePlayBtn.frame = CGRectMake(40.0110.0240.030.0);
    [movePlayBtn setTitle:@"Play Move" forState:UIControlStateNormal];
    [movePlayBtn addTarget:self action:@selector(playMovie:) forControlEvents:UIControlEventTouchUpInside];

    //...
    [[self view] addSubview:musicPlayBtn];
    [[self view] addSubview:movePlayBtn];
}

 播放音乐按钮实现://退出后,再进入,音乐接着播放,按钮变为play,需要解决方案。

- (void)playMusic:(id)sender
{
    if ([audioPlayer isPlaying]) {
        [audioPlayer stop];
        [sender setTitle:@"Play Music" forState:UIControlStateNormal];
    }
    else
    {
        [audioPlayer play];
        [sender setTitle:@"Stop Music" forState:UIControlStateNormal];
    }
}

 视频播放:

- (void)playMovie:(id)sender
{
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"big" ofType:@"m4v"];
    if (moviePath) {
        NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
        moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMoviePlay:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
    moviePlayer.view.frame = CGRectMake(40.0150.0240.0140.0);//播放完成
    [[self view] addSubview:[moviePlayer view]];
}

 //添加通知,当视频播放完成,从view移除

- (void)stopMoviePlay:(id)sender
{
    MPMoviePlayerController *mp = [sender object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:mp];
    [[moviePlayer view] removeFromSuperview];
}

打开FirstApp-Info.plist文件,添加Required background modes,设置item0值为App plays audio。支持音乐后台播放。(模拟器不支持)

posted @ 2012-05-14 13:25  Maxfong  阅读(541)  评论(0编辑  收藏  举报