您的位置:首页 > 移动开发 > IOS开发

IOS上MediaPlayer.framework实现视频播放

2015-04-22 11:45 645 查看
播放电影文件:

    iOS sdk中可以使用MPMoviePlayerController来播放电影文件。但是在iOS设备上播放电影文件有严格的格式要求,只能播放下面两个格式的电影文件。

• H.264 (Baseline Profile Level 3.0)

• MPEG-4 Part 2 video (Simple Profile)

MPMoviePlayerController可以播放本地视频文件,也可以播放互联网上的视频文件。

首先在项目中需要引入Media Player 框架

项目-->Targets-->Build Phases-->Link Binary With Libraries

点击左下角的+号



找到MediaPlayer.framework并添加



在需要使用库的地方添加下面的代码:

[cpp]
view plaincopy

#import <MediaPlayer/MediaPlayer.h>  

本项目名为MediaPlayerTest,源码如下:

VideoPlayerViewController.h 头文件代码:

[cpp]
view plaincopy

#import <UIKit/UIKit.h>  
#import <MediaPlayer/MediaPlayer.h>  
  
@interface ViewController : UIViewController  
{  
    UIButton *playBtn;  
    MPMoviePlayerController *moviePlayer;  
}  
  
@property (retain, nonatomic) IBOutlet UIButton *playBtn;  
@property (retain, nonatomic) MPMoviePlayerController *moviePlayer;  
  
- (IBAction)playVideo:(id)sender;  
@end  

VideoPlayerViewController.m 实现文件代码:

[cpp]
view plaincopy

#import "ViewController.h"  
#import <MediaPlayer/MediaPlayer.h>  
  
@interface ViewController ()  
  
@end  
  
@implementation ViewController  
@synthesize playBtn;  
@synthesize moviePlayer;  
  
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:  
                        [NSURL URLWithString:@"http://v.youku.com/player/getRealM3U8/vid/XNTY2MTAxOTUy/type/video.m3u8"]];  
    self.moviePlayer.movieControlMode = MPMovieControlModeDefault;  
    [self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 380)];  
   
    // Do any additional setup after loading the view, typically from a nib.  
}  
  
- (void)didReceiveMemoryWarning  
{  
    [super didReceiveMemoryWarning];  
    // Dispose of any resources that can be recreated.  
}  

4000
  
- (IBAction)playVideo:(id)sender  
{  
    NSLog(@"Into playvideo.");  
    [self.view insertSubview:[self.moviePlayer view] atIndex:10];  
    [self.moviePlayer play];  
}  
  
@end  

MainStoryboard.storyboard:

将ViewController的playBtn和IB的Button关联起来



将Button的Touch Up Inside事件和View Controller的playVideo操作关联起来



运行结果:





使用MPMoviePlayerController类实现视频播放器

MPMoviePlayerController类可以播放多媒体文件,视频文件可以位于App文件系统中,或者远程URL处。下面是基于MPMoviePlayerController类实现的一个视频播放器App,项目名称 VideoPlayer。

开发环境:Xcode 4.5 + iOS 6 iPhone 模拟器

视频播放器VideoPlayer 运行界面:

首先在项目中需要引入Media Player 框架,并在相应的类中添加接口文件的引用:

#import <MediaPlayer/MediaPlayer.h>

本示例项目全部源代码如下,代码中详细的注释。

VideoPlayerViewController.h 头文件代码:

#import <UIKit/UIKit.h>

#import <MediaPlayer/MediaPlayer.h>


@interface VideoPlayerViewController : UIViewController


@property (strong, nonatomic) MPMoviePlayerController *moviePlayer;

- (IBAction)playVideo:(id)sender;



 

 

@end


VideoPlayerViewController.m [b]实现文件代码:[/b]

#import "VideoPlayerViewController.h"


@interface VideoPlayerViewController ()


@end



@implementation VideoPlayerViewController

- (void)viewDidLoad

{

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

// 获取视频文件路径

NSString *movieFile = [[NSBundle mainBundle] pathForResource:@"Mr-Taxi" ofType:@"mp4"];
// 设置视频播放器

self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:movieFile]];

self.moviePlayer.allowsAirPlay = YES;

[self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 380)];

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (IBAction)playVideo:(id)sender {
// 将moviePlayer的视图添加到当前视图中

[self.view addSubview:self.moviePlayer.view];
// 播放完视频之后,MPMoviePlayerController 将发送

// MPMoviePlayerPlaybackDidFinishNotification 消息

// 登记该通知,接到该通知后,调用playVideoFinished:方法

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];

[self.moviePlayer play];

}

 

 

- (void)playVideoFinished:(NSNotification *)theNotification{
// 取消监听

[[NSNotificationCenter defaultCenter]

removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
// 将视频视图从父视图中删除

[self.moviePlayer.view removeFromSuperview];

}

@end


iOS开发之多媒体播放

iOS sdk中提供了很多方便的方法来播放多媒体。本文将利用这些SDK做一个demo,来讲述一下如何使用它们来播放音频文件。

AudioToolbox framework

    使用AudioToolbox framework。这个框架可以将比较短的声音注册到 system sound服务上。被注册到system sound服务上的声音称之为 system sounds。它必须满足下面几个条件。

1、 播放的时间不能超过30秒

2、数据必须是 PCM或者IMA4流格式

3、必须被打包成下面三个格式之一:Core Audio Format (.caf), Waveform audio (.wav), 或者 Audio Interchange File (.aiff)

    声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:

#import <AudioToolbox/AudioToolbox.h>
@interface MediaPlayerViewController : UIViewController
{
IBOutlet UIButton *audioButton;
SystemSoundID shortSound;
}


- (id)init
{
self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];
if (self) {
// Get the full path of Sound12.aif
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"
ofType:@"aif"];
// If this file is actually in the bundle...
if (soundPath) {
// Create a file URL with this path
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];

// Register sound file located at that URL as a system sound
OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL,
&shortSound);
if (err != kAudioServicesNoError)
NSLog(@"Could not load %@, error code: %d", soundURL, err);
}
}
return self;
}


这样就可以使用下面代码播放声音了:

- (IBAction)playShortSound:(id)sender
{
AudioServicesPlaySystemSound(shortSound);
}


使用下面代码,还加一个震动的效果:

- (IBAction)playShortSound:(id)sender
{
AudioServicesPlaySystemSound(shortSound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}


AVFoundation framework

   对于压缩过Audio文件,或者超过30秒的音频文件,可以使用AVAudioPlayer类。这个类定义在AVFoundation framework中。

    下面我们使用这个类播放一个mp3的音频文件。首先要引入AVFoundation framework,然后MediaPlayerViewController.h中添加下面代码:

#import <AVFoundation/AVFoundation.h>
@interface MediaPlayerViewController : UIViewController <AVAudioPlayerDelegate>
{
IBOutlet UIButton *audioButton;
SystemSoundID shortSound;
AVAudioPlayer *audioPlayer;


    AVAudioPlayer类也是需要知道音频文件的路径,使用下面代码创建一个AVAudioPlayer实例:

- (id)init
{
self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];

if (self) {

NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"Music"
ofType:@"mp3"];
if (musicPath) {
NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL
error:nil];
[audioPlayer setDelegate:self];
}
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"
ofType:@"aif"];


我们可以在一个button的点击事件中开始播放这个mp3文件,如:

- (IBAction)playAudioFile:(id)sender
{
if ([audioPlayer isPlaying]) {
// Stop playing audio and change text of button
[audioPlayer stop];
[sender setTitle:@"Play Audio File"
forState:UIControlStateNormal];
}
else {
// Start playing audio and change text of button so
// user can tap to stop playback
[audioPlayer play];
[sender setTitle:@"Stop Audio File"
forState:UIControlStateNormal];
}
}


这样运行我们的程序,就可以播放音乐了。

这个类对应的AVAudioPlayerDelegate有两个委托方法。一个是 audioPlayerDidFinishPlaying:successfully: 当音频播放完成之后触发。当播放完成之后,可以将播放按钮的文本重新回设置成:Play Audio File

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
[audioButton setTitle:@"Play Audio File"
forState:UIControlStateNormal];
}


另一个是audioPlayerEndInterruption:,当程序被应用外部打断之后,重新回到应用程序的时候触发。在这里当回到此应用程序的时候,继续播放音乐。

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
[audioPlayer play];
}


MediaPlayer framework

播放电影文件:

    iOS sdk中可以使用MPMoviePlayerController来播放电影文件。但是在iOS设备上播放电影文件有严格的格式要求,只能播放下面两个格式的电影文件。

• H.264 (Baseline Profile Level 3.0)

• MPEG-4 Part 2 video (Simple Profile)

幸运的是你可以先使用iTunes将文件转换成上面两个格式。

MPMoviePlayerController还可以播放互联网上的视频文件。但是建议你先将视频文件下载到本地,然后播放。如果你不这样做,iOS可能会拒绝播放很大的视频文件。

这个类定义在MediaPlayer framework中。在你的应用程序中,先添加这个引用,然后修改MediaPlayerViewController.h文件。

#import <MediaPlayer/MediaPlayer.h>
@interface MediaPlayerViewController : UIViewController <AVAudioPlayerDelegate>
{
MPMoviePlayerController *moviePlayer;


下面我们使用这个类来播放一个.m4v 格式的视频文件。与前面的类似,需要一个url路径。

- (id)init
{
self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];
if (self) {

NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"Layers"
ofType:@"m4v"];
if (moviePath) {
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:movieURL];
}


MPMoviePlayerController有一个视图来展示播放器控件,我们在viewDidLoad方法中,将这个播放器展示出来。

- (void)viewDidLoad
{
[[self view] addSubview:[moviePlayer view]];
float halfHeight = [[self view] bounds].size.height / 2.0;
float width = [[self view] bounds].size.width;
[[moviePlayer view] setFrame:CGRectMake(0, halfHeight, width, halfHeight)];
}


还有一个MPMoviePlayerViewController类,用于全屏播放视频文件,用法和MPMoviePlayerController一样。

MPMoviePlayerViewController *playerViewController =
[[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[viewController presentMoviePlayerViewControllerAnimated:playerViewController];


   我们在听音乐的时候,可以用iphone做其他的事情,这个时候需要播放器在后台也能运行,我们只需要在应用程序中做个简单的设置就行了。

1、在Info property list中加一个 Required background modes节点,它是一个数组,将第一项设置成设置App plays audio。

2、在播放mp3的代码中加入下面代码:

if (musicPath) {
NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
[[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryPlayback error:nil];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL
error:nil];
[audioPlayer setDelegate:self];
}


在后台运行的播放音乐的功能在模拟器中看不出来,只有在真机上看效果。



总结:本文通过例子详细讲解了iOS sdk中用于播放音频文件的类,文章后面有本文的代码提供下载。

代码:http://files.cnblogs.com/zhuqil/MediaPlayer.zip

作者:朱祁林 出处:http://zhuqil.cnblogs.com 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息