iOS开发之多媒体播放

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

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

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

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

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

  1. - (IBAction)playShortSound:(id)sender 
  2.     AudioServicesPlaySystemSound(shortSound); 
  3.     AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 

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.      
  4.     if (self) { 
  5.      
  6.         NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"Music" 
  7.                                                               ofType:@"mp3"]; 
  8.         if (musicPath) { 
  9.             NSURL *musicURL = [NSURL fileURLWithPath:musicPath]; 
  10.             audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL  
  11.                                                                  error:nil]; 
  12.             [audioPlayer setDelegate:self]; 
  13.         } 
  14.         NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12" 
  15.                                                               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.     } 
  8.     else { 
  9.         // Start playing audio and change text of button so 
  10.         // user can tap to stop playback 
  11.         [audioPlayer play]; 
  12.         [sender setTitle:@"Stop Audio File" 
  13.                 forState:UIControlStateNormal]; 
  14.     } 

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

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

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

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

  1. - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player 
  2.     [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文件。

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

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

  1. - (id)init 
  2.     self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil]; 
  3.     if (self) { 
  4.      
  5.         NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"Layers"  
  6.                                                               ofType:@"m4v"]; 
  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)]; 

还有一个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]; 
  8.     } 

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

责任编辑:张叶青 来源: 博客园
相关推荐

2011-08-02 10:36:02

iOS开发 SDK 多媒体

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多媒体播放解决方案

2011-06-24 10:21:11

Qt phonon 多媒体

2017-03-01 14:01:31

android多媒体音乐代码

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

2010-06-30 10:38:05

2011-06-09 10:07:28

Qt phonon

2018-05-25 14:37:58

2009-12-25 17:02:33

WPF多媒体

2010-10-27 11:27:50

MAS视频监控H3C

2020-12-20 09:05:30

腾讯多媒体5G

2014-09-24 11:04:31

微信企业号开发

2009-12-22 16:29:51

Linux多媒体软件
点赞
收藏

51CTO技术栈公众号