了解iOS开发之多媒体播放

移动开发 iOS
本文将利用这些SDK做一个demo,来讲述一下如何使用它们来播放音频文件,使用AudioToolbox framework。这个框架可以将比较短的声音注册到 system sound服务上,来看详细内容。

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对象。看下面注册代码:

  1. #import <AudioToolbox/AudioToolbox.h> 
  2. @interface MediaPlayerViewController : UIViewController{      
  3. IBOutlet UIButton *audioButton;      
  4. SystemSoundID shortSound;}- (id)init{      
  5. self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];      
  6. if (self) {          
  7. // Get the full path of Sound12.aif          
  8. NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"    
  9.                                               ofType:@"aif"];          
  10. // If this file is actually in the bundle...         
  11.  if (soundPath) {              
  12.  // Create a file URL with this path             
  13.   NSURL *soundURL = [NSURL fileURLWithPath:soundPath];   
  14. // Register sound file located at that URL as a system sound             
  15.  OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL,    
  16.                                       &shortSound);              
  17.        if (err != kAudioServicesNoError)                 
  18.         NSLog(@"Could not load %@, error code: %d", soundURL, err);  
  19.     }      
  20.   }     
  21. return self;  

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

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

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

  1. - (IBAction)playShortSound:(id)sender{      
  2. AudioServicesPlaySystemSound(shortSound);      
  3. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);}  
  4. AVFoundation framework 

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

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

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

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

  1. - (id)init{  
  2.     self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];  
  3.       if (self) {  
  4.                   NSString *musicPath = [[NSBundle mainBundle]  pathForResource:@"Music"     
  5.         ofType:@"mp3"];          
  6.       if (musicPath) {   
  7.                  NSURL *musicURL = [NSURL fileURLWithPath:musicPath];  
  8.                audioPlayer = [[AVAudioPlayer alloc]  initWithContentsOfURL:musicURL     
  9.                       error:nil];   
  10.                [audioPlayer setDelegate:self];        
  11.     }          
  12.     NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"      
  13.  ofType:@"aif"]; 

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

  1. - (IBAction)playAudioFile:(id)sender{  
  2.     if ([audioPlayer isPlaying]) {  
  3.             // Stop playing audio and change text of button  
  4.               [audioPlayer stop];          
  5.               [sender setTitle:@"Play Audio File"   
  6.               forState:UIControlStateNormal];  
  7.     }    else {         
  8.     // Start playing audio and change text of button so    
  9.     // user can tap to stop playback    
  10.     [audioPlayer play];          
  11.     [sender setTitle:@"Stop Audio File"     
  12.     forState:UIControlStateNormal];  
  13.    }  

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

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

  1. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player   
  2.                       successfully:(BOOL)flag  
  3.               {      
  4.            [audioButton setTitle:@"Play Audio File"  
  5.                             forState:UIControlStateNormal];  
  6.             } 

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

  1. - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player{    [audioPlayer play];}  
  2. MediaPlayer framework 

播放电影文件:

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

  1. • H.264 (Baseline Profile Level 3.0)  
  2. • MPEG-4 Part 2 video (Simple Profile) 

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

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

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

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

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

  1. - (id)init{     
  2.  self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];  
  3.     if (self) {            NSString *moviePath = [[NSBundle mainBundle]   
  4.     pathForResource:@"Layers"       
  5.     ofType:@"m4v"  
  6.   ];         
  7.    if (moviePath) {            
  8.      NSURL *movieURL = [NSURL fileURLWithPath:moviePath];              
  9.      moviePlayer = [[MPMoviePlayerController alloc]                                       
  10.      initWithContentURL:movieURL];          
  11.  } 

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

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

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

  1. MPMoviePlayerViewController *playerViewController =  
  2.     [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];    
  3. [viewController presentMoviePlayerViewControllerAnimated:playerViewController]; 

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

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

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

  1. if (musicPath) {          
  2. NSURL *musicURL = [NSURL fileURLWithPath:musicPath];          
  3. [[AVAudioSession sharedInstance]                     
  4.            setCategory:AVAudioSessionCategoryPlayback error:nil];          
  5. audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL     
  6.                                error:nil];          
  7.        [audioPlayer setDelegate:self];  

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

了解iOS开发之多媒体播放

小结:了解iOS开发多媒体播放的内容介绍完了,本文通过例子详细讲解了iOS SDK中用于播放音频文件的类,最后希望本文对你有所帮助!本文提供代码供友们方便的去学习,代码下载地址:http://files.cnblogs.com/zhuqil/MediaPlayer.zip

责任编辑:zhaolei 来源: 博客园
相关推荐

2013-12-17 13:29:04

iOS开发多媒体

2013-12-17 11:18:53

iOS开发多媒体API

2021-09-13 15:15:18

鸿蒙HarmonyOS应用

2010-01-27 16:21:29

Android多媒体播

2009-02-18 17:15:51

Fedora 10多媒体播放解决方案

2017-03-01 14:01:31

android多媒体音乐代码

2011-06-24 10:21:11

Qt phonon 多媒体

2011-08-18 17:07:23

IOS开发多线程NSInvocatio

2013-08-28 16:08:19

多媒体Windows8.1

2022-11-25 16:39:03

视频播放鸿蒙

2022-11-23 14:43:40

2010-08-01 15:34:27

Android

2011-06-09 10:07:28

Qt phonon

2010-06-30 10:38:05

2018-05-25 14:37:58

2009-12-25 17:02:33

WPF多媒体

2010-10-27 11:27:50

MAS视频监控H3C

2014-09-24 11:04:31

微信企业号开发

2015-09-11 11:02:23

ios静态库开发

2020-12-20 09:05:30

腾讯多媒体5G
点赞
收藏

51CTO技术栈公众号