iOS開發之多媒體播放

來源:互聯網
上載者:User

標籤:des   style   http   io   ar   os   使用   sp   for   

本文轉載至 http://mobile.51cto.com/iphone-423284.htm

 

iOS sdk中提供了很多方便的方法來播放多媒體。本文將利用這些SDK做一個demo,來講述一下如何使用它們來播放音頻檔案。

AD:2014WOT全球軟體技術峰會北京站 課程視頻發布

 

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.     } 

在後台啟動並執行播放音樂的功能在模擬器中看不出來,只有在真機上看效果。

iOS開發之多媒體播放

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.