播放视频

视频文件介绍

视频格式可以分为适合本地播放的本地影像视频和适合在网络中播放的网络流媒体影像视频两大类。尽管后者在播放的稳定性和播放画面质量上可能没有前者 优秀,但网络流媒体影像视频的广泛传播性使之正被广泛应用于视频点播、网络演示、远程教育、网络视频广告等等互联网信息服务领域。

适合移动设备的视频文件

3GP,3GP是一种3G流媒体的视频编码格式,主要是为了配合3G网络的高传输速度而开发的,也是目前手机中最为常见的一种视频格式。 视频MP4格式,除了支持MP3所具有的音乐播放功能外,还具备强大的MPEG-4视频播放能力。

iPhone中还支持mov格式文件。

iOS播放视频 

iOS sdk为播放视频提供了非常简便方法,提供的MPMoviePlayerViewController类作为开发使用,在iOS4以前的版本是MPMoviePlayerController。

在iPhone开发规范中禁止使用私有API播放视频,因此播放画面的控制的控件都是有iPhone提供好的,我们没有别的选择。我们能做的:

加载URL中视频

播放、暂停视频

用户控制行为和缩放模式

产生通知

视频播放案例

添加 MediaPlayer.framework

MoviePlayerViewController.h

  1. #import <MediaPlayer/MediaPlayer.h>
  2. @interface MoviePlayerViewController : UIViewController {
  3. MPMoviePlayerViewController * moviePlayerView;
  4. }
  5. @property (nonatomic, retain) MPMoviePlayerViewController * moviePlayerView;
  6. -(IBAction) playMovie: (id) sender;
  7. - (void) playingDone;
  8. @end

m文件的加载和卸载方法

  1. - (void) viewDidLoad {
  2. [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(playingDone) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
  3. }
  4. - (void)dealloc {
  5. [[NSNotificationCenter defaultCenter] removeObserver:self];
  6. [moviePlayerView release];
  7. [super dealloc];
  8. }

MPMoviePlayerViewController提供了在播放过程中的状态改变和其它事件的通知。在viewDidLoad注册了一个播放完成的通知,常用的通知有:

MPMoviePlayerPlaybackDidFinishNotification通知接收者播放结束。

MPMoviePlayerScalingModeDidChangeNotification改变影片的尺寸。

MPMoviePlayerContentPreloadDidFinishNotification表示预处理以及完成,准备开始播放影片。

dealloc方法中的[[NSNotificationCenter defaultCenter]

removeObserver:self];影片播放完成要注销通知。

播放事件

  1. - (IBAction) playMovie: (id) sender {
  2. moviePlayerView = [[MPMoviePlayerViewController alloc]
  3. initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
  4. pathForResource:@"short" ofType:@"3gp"]]];
  5. moviePlayerView.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
  6. moviePlayerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
  7. // MPMovieControlStyleNone
  8. //MPMovieControlStyleEmbedded
  9. //MPMovieControlStyleDefault
  10. //[movieplayer play];
  11. //在当前view上添加视频的视图
  12. [[[UIApplication sharedApplication] keyWindow] addSubview:moviePlayerView.view];
  13. }

视频文件可以播放资源目录、沙箱目录和网络播放。本例中我们采用资源目录。

moviePlayerView.moviePlayer属性是MPMoviePlayerController类型,它有的controlStyle属性

可以控制播放行为,它的取值有:

MPMovieControlStyleFullscreen

MPMovieControlStyleNone没有播放控件

MPMovieControlStyleEmbedded

MPMovieControlStyleDefault

MPMoviePlayerController类还有scalingMode属性用于控制影片的尺寸,它的取值有:

MPMovieScalingModeNone原始尺寸

MPMovieScalingModeAspectFit缩放到一个填充方向

MPMovieScalingModeAspectFill填充两边可能会切除一部分

MPMovieScalingModeFill填充两边可能会改变比例

播放完成

  1. - (void) playingDone {
  2. NSLog(@"播放完成");
  3. [moviePlayerView.view removeFromSuperview];
  4. [moviePlayerView release];
  5. moviePlayerView = nil;
  6. }

playingDone 方法是在影片播放完成时候调用,这是因为我们在通知中心注册的方法。

播放完成需要把播放视图remove这样才可以获得上一个屏幕。

12.2 播放音频

12.2.1 音频文件介绍

有两类主要的音频文件格式:

无损格式,例如WAV,PCM,TTA,FLAC,AU,APE,TAK,WavPack(WV) ,CAF

有损格式,例如MP3,Windows Media Audio(WMA),Ogg Vorbis(OGG),AAC

移动音频文件

作为移动设备音频文件应该原则上比较小,一般的格式:

WAV、由于无损压缩效果最好。

MP3、有损压缩,文件比较小,由于去除的是人类无法感应到的声音,效果也很好。这是目前常用格式。

AAC、压缩比例更大,比MP3文件还要小。

CAF(Core Audio Format)是Apple专用的无损压缩格式。

12.2.2 Core Audio

高级API,易用

System Sound API –播放短声音、警告音等。

AVFoundation 可以播放长时间声音,简单易用。

低级API,能够对音频有更多的控制

Audio Toolbox – 录制、播放、音频流有全面的控制。

OpenAL – 播放立体声,常用于游戏。

12.2.3 System Sound API

System Sound 可以播放“短的”声音,所谓短声音就是5秒以内。 不循环、没有声音控制、立即播放。

播放格式限制:

线性PCM 和 IMA4

.caf .aif 或 .wav

播放“短声音”

播放“短声音”主要就是两个步骤:

注册声音

  1. AudioServicesCreateSystemSoundID ((CFURLRef)fileURL, &myID);

播放声音

  1. AudioServicesPlaySystemSound (myID);

监听完成事件方法

  1. AudioServicesAddSystemSoundCompletion

清除播放sound ID

  1. SystemSoundID myID;
  2. AudioServicesDisposeSystemSoundID (myID);

震动

也可以通过System Sound API让iPhone震动,但是iPod touch不能震动。

震动可以通过指定一个特殊的system sound ID—— kSystemSoundID_Vibrate实现。

AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);

实例

SystemSoundServices

添加AudioToolbox.framework框架

SystemSoundServicesViewController.h文件

 
  1. #import <UIKit/UIKit.h>
  2. #include <AudioToolbox/AudioToolbox.h>
  3. @interface SystemSoundServicesViewController : UIViewController;
  4. - (IBAction) playSystemSound;
  5. - (IBAction) vibrate;
  6. @end

播放事件

  1. - (IBAction) playSystemSound{
  2. NSURL* system_sound_url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"BeepGMC500" ofType:@"wav"]];
  3. SystemSoundID system_sound_id;
  4. AudioServicesCreateSystemSoundID(
  5. (CFURLRef)system_sound_url,
  6. &system_sound_id
  7. );
  8. // Register the sound completion callback.
  9. AudioServicesAddSystemSoundCompletion(
  10. system_sound_id,
  11. NULL, // uses the main run loop
  12. NULL, // uses kCFRunLoopDefaultMode
  13. MySoundFinishedPlayingCallback, // the name of our custom callback function
  14. NULL // for user data, but we don't need to do that in this case, so we just pass NULL
  15. );
  16. // Play the System Sound
  17. AudioServicesPlaySystemSound(system_sound_id);
  18. }

AudioServicesAddSystemSoundCompletion方法5个参数,第一参数SystemSoundID,第二参数是是否使用循环,第三个参数是循环模式,第四个参数是回调函数,就是当播放完成时候回调的方法,第五个参数是为回调函数提供参数。

这里回调的方法是C语言风格的函数:MySoundFinishedPlayingCallback。

回调函数

  1. void MySoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data){
  2. AudioServicesDisposeSystemSoundID(sound_id);
  3. }

震动方法调用

  1. // Vibrate on action
  2. - (IBAction) vibrate{
  3. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
  4. }

12.3 播放和录制音频

AVFoundation控件可以实现一般音频播放和录制。

AVAudioPlayer音频播放类,用于播放大于5秒钟声音,可以播放本地声音,但是不能播放网络媒体文件。能够播放、 暂停、循环和跳过等操作。

AVAudioRecorder音频录制类。

实例AVAudioPlayer

添加AVFoundation.framework框架

AvplayerViewController.h文件

  1. #import <UIKit/UIKit.h>
  2. #import <AVFoundation/AVFoundation.h>
  3. @interface AvplayerViewController : UIViewController <AVAudioPlayerDelegate> {
  4. AVAudioPlayer * player;
  5. }
  6. - (IBAction) stopSong: (id) sender;
  7. - (IBAction) playSong: (id) sender;
  8. @end

AvplayerViewController.m

  1. #import "AvplayerViewController.h"
  2. @implementation AvplayerViewController
  3. - (IBAction) playSong: (id) sender {
  4. NSError *error = nil;
  5. player = [[AVAudioPlayer alloc] initWithContentsOfURL:
  6. [NSURL fileURLWithPath:[[NSBundle mainBundle]
  7. pathForResource:@"charleston1925_64kb" ofType:@"mp3"]] error:&error];
  8. player.delegate = self;
  9. if(error) {
  10. NSLog(@"%@",[error description]);
  11. [error release];
  12. }
  13. [player play];
  14. }
  15. - (IBAction) stopSong: (id) sender {
  16. [player stop];
  17. }
  18. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
  19. NSLog(@"播放完成。");
  20. }
  21. - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
  22. NSLog(@"播放错误发生: %@", [error localizedDescription]);
  23. }
  24. - (void)dealloc {
  25. [player release];
  26. [super dealloc];
  27. }
  28. @end

AVAudioPlayer委托

AVAudioPlayerDelegate委托对象提供了两个主要方法:

audioPlayerDidFinishPlaying:successfully:

audioPlayerDecodeErrorDidOccur:error:

AVAudioRecorder

新建实例:Recorder

RecorderViewController.h文件

  1. #import <UIKit/UIKit.h>
  2. #import <AVFoundation/AVFoundation.h>
  3. @interface RecorderViewController : UIViewController
  4. {
  5. AVAudioRecorder *recorder;
  6. AVAudioPlayer *player;
  7. UILabel *label;
  8. }
  9. @property (retain, nonatomic) AVAudioRecorder * recorder;
  10. @property (retain, nonatomic) AVAudioPlayer * player;
  11. @property (retain, nonatomic) IBOutlet UILabel *label;
  12. -(IBAction)recordPushed:(id)sender;
  13. -(IBAction)playPushed:(id)sender;
  14. -(IBAction)stopPushed:(id)sender;
  15. @end

音频录制方法

  1. -(IBAction)recordPushed:(id)sender
  2. {
  3. label.text = @"recode...";
  4. if([recorder isRecording])
  5. return;
  6. if([player isPlaying])
  7. [player stop];
  8. NSError *error = nil;
  9. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord
  10. error:&error];
  11. [[AVAudioSession sharedInstance] setActive:YES error:&error];

AVAudioSession 是iOS提供音频会话类,音频会话是指定应用程序与音频系统如何交互。AVAudioSession 通过指定一个音频类别(Category)实现的,音频类别(Category)描述了应用程序使用音频的方式。下面是语句是设定音频会话类别:

[[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryRecord error:&error];

AVAudioSessionCategoryRecord代表只能输入音频,即录制音频了。其效果是停止其它音频播放。

使用类别后,音频会话要设置为“活跃的”Active,这会把后台的任何系统声音关闭。

[[AVAudioSession sharedInstance]  setActive:YES error:&error];

音频录制方法

  1. NSMutableDictionary *settings = [NSMutableDictionary dictionary];
  2. [settings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM]
  3. forKey:AVFormatIDKey];
  4. [settings setValue:[NSNumber numberWithFloat:44100.0]
  5. forKey:AVSampleRateKey]; //采样率
  6. [settings setValue:[NSNumber numberWithInt:1]
  7. forKey:AVNumberOfChannelsKey];//通道的数目
  8. [settings setValue:[NSNumber numberWithInt:16]
  9. forKey:AVLinearPCMBitDepthKey];//采样位数  默认 16
  10. [settings setValue:[NSNumber numberWithBool:NO]
  11. forKey:AVLinearPCMIsBigEndianKey];//大端还是小端 是内存的组织方式
  12. [settings setValue:[NSNumber numberWithBool:NO]
  13. forKey:AVLinearPCMIsFloatKey];//采样信号是整数还是浮点数
  14. NSString *filePath =
  15. [NSString stringWithFormat:@"%@/rec_audio.caf", [self documentsDirectory]];
  16. NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
  17. //[self setRecorder:nil];
  18. recorder = [[AVAudioRecorder alloc]
  19. initWithURL:fileUrl
  20. settings:settings
  21. error:&error];
  22. // [recorder setMeteringEnabled:YES];
  23. [recorder record];
  24. }
-(NSString *)documentsDirectory{     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,                                                           NSUserDomainMask, YES);      return [paths objectAtIndex:0]; }

音频播放方法

  1. -(IBAction)playPushed:(id)sender{
  2. label.text = @"play...";
  3. if([recorder isRecording])
  4. [recorder stop];
  5. if([player isPlaying])
  6. [player stop];
  7. NSString *filePath =
  8. [NSString stringWithFormat:@"%@/rec_audio.caf", [self documentsDirectory]];
  9. NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
  10. NSError *error = nil;
  11. // [self setPlayer:nil];
  12. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
  13. error:&error];
  14. [[AVAudioSession sharedInstance] setActive:YES error:&error];
  15. player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
  16. // [player setMeteringEnabled:YES];
  17. [player play];
  18. }

音频停止方法

  1. -(IBAction)stopPushed:(id)sender{
  2. label.text = @"stop...";
  3. if([recorder isRecording])
  4. [recorder stop];
  5. if([player isPlaying])
  6. [player stop];
  7. }

iOS开发之多媒体API的更多相关文章

  1. iOS开发之多媒体API(1)

    iOS开发之多媒体API(1)       播放视频 视频文件介绍 视频格式可以分为适合本地播放的本地影像视频和适合在网络中播放的网络流媒体影像视频两大类.尽管后者在播放的稳定性和播放画面质量上可能没 ...

  2. iOS开发之多媒体API (转载)

    视频格式可以分为适合本地播放的本地影像视频和适合在网络中播放的网络流媒体影像视频两大类.尽管后者在播放的稳定性和播放画面质量上可能没有前者 优秀,但网络流媒体影像视频的广泛传播性使之正被广泛应用于视频 ...

  3. iOS开发UITouch触摸API简介

    1.UITouch简介 当用户触摸屏幕时,会创建一个UITouch对象: UITouch的作用保存着触摸相关的信息,比如触摸的位置.时间.阶段等: 当从开始到结束,系统会更新UITouch对象,结束时 ...

  4. iOS开发UIResponder简介API

    #import <Foundation/Foundation.h> #import <UIKit/UIKitDefines.h> #import <UIKit/UIEve ...

  5. iOS开发中的Html解析方法

    iOS开发中的Html解析方法 本文作者为大家介绍了在iOS开发中的Html解析方法,并同时提供了Demo代码的下载链接,Demo 解析了某个网站(具体可在代码中查看)的html网页,提取了图片以及标 ...

  6. iOS开发-Objective-C Block的实现方式

    前言:我们可以把Block当作一个闭包函数,它可以访问外部变量和局部变量,但默认是不可以修改外部变量.你可以使用它来做回调方法,比起使用代理(Delegate)会更加直观.顺带一提,苹果很多的接口(A ...

  7. iOS开发API常用英语名词

    iOS开发API常用英语名词 0. indicating 决定 1.in order to 以便 2.rectangle bounds 矩形尺寸 3.applied 应用 4.entirety 全部 ...

  8. iOS开发系列--音频播放、录音、视频播放、拍照、视频录制

    --iOS多媒体 概览 随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制, ...

  9. iOS开发----音频播放、录音、视频播放、拍照、视频录制

    随着移动互联网的发展,如今的手机早已不是打电话.发短信那么简单了,播放音乐.视频.录音.拍照等都是很常用的功能.在iOS中对于多媒体的支持是非常强大的,无论是音视频播放.录制,还是对麦克风.摄像头的操 ...

随机推荐

  1. WARNING OGG-01223 TCP/IP error 111 (Connection refused)

    一:问题描述 GGSCI (source_pc) 64> info all Program     Status      Group       Lag at Chkpt  Time Sinc ...

  2. :after伪类+content内容生成经典应用举例

    一.简单说说content内容生成 content内容生成就是通过content属性生成内容,content属性早在CSS2.1的时候就被引入了,可以使用:before以及:after伪元素生成内容. ...

  3. 文成小盆友python-num14 - web 前端基础 html ,css, JavaScript

    本部分主要内容 html - 基础 css - 基础 一.html 标签 html 文档标签树如下: head 部分 Meta(metadata information) 提供有关页面的元信息,例:页 ...

  4. NET Core驱动已出,支持EF Core

    NET Core驱动已出,支持EF Core 千呼万唤始出来MySQL官方.NET Core驱动已出,支持EF Core. 昨天MySQL官方已经发布了.NET Core 驱动,目前还是预览版,不过功 ...

  5. 64位系统ADB

    应该把ADB文件放在C:\Windows\SysWOW64目录下面,而不是System32下.

  6. 转:C语言申请内存时堆栈大小限制

    一直都有一个疑问,一个进程可以使用多大的内存空间,swap交换空间以及物理内存的大小,ulimit的stack size对进程的内存使用有怎样的限制?今天特亲自动手实验了一次,总结如下: 开辟一片内存 ...

  7. 系统共享内存的修改(ORA-27102: out of memory)

    http://ccchencheng.blog.51cto.com/2419062/738188 http://blog.csdn.net/leshami/article/details/874602 ...

  8. Highly divisible triangular number

    我的那个暴力求解,太耗时间了. 用了网上产的什么因式分解,质因数之类的.确实快!还是数学基础不行,只能知道大约. The sequence of triangle numbers is generat ...

  9. PowerShell控制台输出符号+函数参数类型指定+文本内容读取

    There are several ways: Write-Host: Write directly to the console, not included in function/cmdlet o ...

  10. git设置过滤忽略的文件或文件夹

    我们一般向代码仓库提交项目的时候,一般需要忽略编译生成的中间文件以及文件夹的提交,因为它们是无用的,而且也会占用仓库的空间.一般只用提交.pro,.sln,makefile,程序源文件等编译必须用到的 ...