iOS學習45之多媒體操作,ios45多媒體
1. 音頻 1> 音頻實現簡述
iOS 裡面共有四種專門實現播放音訊方式:
2> System Sound Services(系統聲音服務)
① System Sound Services 是最底層也是最簡單的聲音播放服務,通過調用 AudioServicesPlaySystemSound 這個函數就可以播放一些簡單的音頻檔案
② 局限性:
1. 聲音長度要小於30秒
2. 格式:IMA4
3. 不能控制播放的進度
4. 調用方法後立即播放聲音
5. 沒有迴圈播放和立體聲音播放
③ 執行個體代碼
CFBundleRef mainBundle; SystemSoundID soundFileObject; mainBundle = CFBundleGetMainBundle (); CFURLRef soundFileURLRef = CFBundleCopyResourceURL (mainBundle, CFSTR ("蔡琴 - 愛斷情傷"), CFSTR ("wav"), NULL); AudioServicesCreateSystemSoundID (soundFileURLRef, &soundFileObject); AudioServicesPlaySystemSound(soundFileObject);
3> OpenAL
① 簡介
OpenAL 是一套跨平台的開源的音頻處理介面
最適合開發遊戲的音頻
OpenAL 包含三個 實體:Listener(聽者)、Source(音源)、 Buffer(緩衝)
Audio Queue Services 主要用來實現錄製音頻,為了簡化音頻檔案的處理,通常還需要使用到 AudioFileServices
② 開發步驟
1.擷取device
2.將context關聯到device
3.將資料放入buffer
4.將buffer連結到一個source
5.播放source
OpenAL資料網址: http://www.devdiv.com/thread-19636-1-1.html
http://www.cocoachina.com/bbs/read.php?tid-112679-page-1.html
相對底層的 API參考:http://blog.csdn.net/midfar/article/details/7233454
4> AVAudioPlayer簡介
我們可以把 AVAudioPlayer 看作是一個進階的播放器,它支援廣泛的音頻格式,如下:
AAC
AMR(AdaptiveMulti-Rate, aformatforspeech)
ALAC(AppleLossless)
iLBC(internetLowBitrateCodec, anotherformatforspeech)
IMA4(IMA/ADPCM)
linearPCM(uncompressed)
MP3(MPEG-1audiolayer3)
5> AVAudioPlayer優勢
支援更多的格式
可以播放任意長度的音頻檔案
支援迴圈播放
可以同步播放多個音頻檔案
控制播放進度以及從音訊任意一點開始播放
6> AVAudioPlayer開發步驟
- 步驟一:AVAudioPlayer 包含在 AVFoundation 架構中,所以開發的時候首先匯入音訊架構 AVFoundation.framework
引入標頭檔
#import <AVFoundation/AVFoundation.h>
- 步驟二: AVAudioPlayer 的初始化的時候需要給一個播放檔案
AVAudioPlayer *avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:檔案路徑 error:nil];
設定初始音量大小 audioPlayer.volume = 1;(0.0 ~ 1.0)
設定音樂播放次數 audioPlayer.numberOfLoops = -1;(只要是負數都是迴圈播放)
播放進度 audioPlayer.currentTime = 0;
預播放
[audioPlayer prepareToPlay];
播放
[audioPlayer play];
暫停
[audioPlayer pause];
停止
[audioPlayer stop];
協議:AVAudioPlayerDelegate
播放完成會調用的代理方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
播放解碼失敗
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error;
7> 簡單代碼執行個體:
// 懶載入- (AVAudioPlayer *)player{ if (_player == nil) { NSString *urlString = [[NSBundle mainBundle] pathForResource:@"南征北戰 - 驕傲的少年" ofType:@"mp3"]; NSURL *url = [NSURL fileURLWithPath:urlString]; _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; _player.delegate = self; // 設定預設的音量 _player.volume = 0.5; } return _player;}// 播放按鈕響應事件- (IBAction)play:(id)sender{ [self.player play];}// 暫停按鈕響應事件- (IBAction)pause:(id)sender{ [self.player pause];}// 停止按鈕響應事件- (IBAction)stop:(id)sender{ [self.player stop];}// 音量滑竿響應事件- (IBAction)changeVolume:(UISlider *)sender{ self.player.volume = sender.value;}
在我的github上有一個較完善的練習代碼,有興趣的小夥伴可以看看!
8> 音訊後台播放
- 首先要修改設定檔,在 Info.plist 檔案中,添加 UIBackGroundModes ,可以添加包括 Audio 在背景播放音頻和視頻裡的聲音,location 保持目前使用者的位置資訊, voip 使用網路電話。添加以上欄位是為了通知系統架構,在應用程式進入後台時候請求在後台繼續播放一段時間,具體播放多久,根據 UIBackGroundTask 去申請一段時間。還可以使用本地通知,預先設定 local notification 來讓應用程式在後台運行。
後台播放音頻設定
AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; [session setCategory:AVAudioSessionCategoryPlayback error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
2. 視頻 1> AVPlayer
iOS 裡面視頻播放用到的是 AVPlayer(包含在AVFoundation架構內)與 AVAudioPlayer 有點類似,但是 AVPlayer 的功能更加強大,它可以用來播放音頻也可以用來播放視頻。而且在播放音頻方面 AVPlayer 可以直接播放網路音頻。
2> 視頻播放實現步驟
- 步驟一:匯入可使用視訊播放的架構AVFoundation.framework
引入標頭檔代碼
#import <AVFoundation/AVFoundation.h>
NSString *playString = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"; // 播放地址 NSURL *playURL = [NSURL URLWithString:playString];
- 步驟三:根據播放的 URL 建立 AVPlayerItem 對象
AVPlayerItem 可以擷取視頻的資訊,當前播放時間,總時間等
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:playURL];
AVPlayerItem 的重要屬性
狀態 status
AVPlayerStatusUnknown,(代表視頻播放出現了未知的問題)
AVPlayerStatusReadyToPlay,(代表視頻可以播放,可以調用 play方法)
AVPlayerStatusFailed(代表視頻無法進行播放了)
loadedTimeRange:代表已經緩衝的進度,監聽此屬性可以在 UI 中更新緩衝進度,也是很有用的一個屬性
- 步驟四:根據 AVPlayerItem 初始化 AVPlayer 對象
@interface ViewController () @property(nonatomic, strong)AVPlayer *player;@end self.player = [[AVPlayer alloc] initWithPlayerItem:item];
- 步驟五:把 AVPlayerLayer 添加到需要播放頁面的 Layer 層
// 設定播放頁面 AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player]; // 設定播放頁面的大小 layer.frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 300); // 設定背景顏色 layer.backgroundColor = [UIColor cyanColor].CGColor; // 設定播放視窗和當前視圖之間的比例顯示內容 layer.videoGravity = AVLayerVideoGravityResizeAspect; // 添加播放視圖到view上 [self.view.layer addSublayer:layer];
// 播放 [self.player play];
[self.player seekToTime:CMTimeMakeWithSeconds(progress,//設定每秒鐘多少幀self.player.currentTime.timescale) completionHandler:^(BOOL finished) { }]; // 設定音量 self.player.volume = 1.0f; // 當前播放時間 self.player.currentTime
//當播放完成時,可以註冊通知,根據需求,做出不同的響應AVPlayerItemDidPlayToEndTimeNotification
可以通過設定觀察者來完成添加播放完成通知
-(void)addNotification{ //給AVPlayerItem添加播放完成通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];}-(void)playbackFinished:(NSNotification *)notification{ NSLog(@"視頻播放完成.");}
通過以上的六個步驟已經可以實現視頻在 iOS 用戶端的播放;
AVPlayerltem 資源管理對象,作用是:切換視訊播放,使用時切換不同的 Item 即可. 而非建立新的 AVPlayer.
AVPlayerItem 的一些重要屬性可以使我們定製視頻的開發
執行個體代碼:
- (void)viewDidLoad { [super viewDidLoad]; NSString *playString = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"; NSURL *url = [NSURL URLWithString:playString]; // 本地視頻// NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1457622279563.mp4" ofType:nil]]; // 設定播放的項目 AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url]; // 初始化player對象 self.player = [[AVPlayer alloc] initWithPlayerItem:item]; // 設定播放頁面 AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player]; // 設定播放頁面的大小 layer.frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 300); // 設定背景顏色 layer.backgroundColor = [UIColor cyanColor].CGColor; // 設定播放視窗和當前視圖之間的比例顯示內容 layer.videoGravity = AVLayerVideoGravityResizeAspect; // 添加播放視圖到view上 [self.view.layer addSublayer:layer]; // 設定播放進度的預設值 self.progressSlider.value = 0; // 設定播放音量的預設值 self.player.volume = 1.0f; [self addNotification];}#pragma mark - 開始播放按鈕的回應程式法- (IBAction)startPlayer:(UIButton *)sender{ [self.player play];}#pragma mark - 暫停播放按鈕的回應程式法- (IBAction)puasePlayer:(UIButton *)sender{ [self.player pause];}#pragma mark - 改變進度按鈕的回應程式法- (IBAction)changeProgress:(UISlider *)sender{ self.sumPlayOperation = _player.currentItem.duration.value / _player.currentItem.duration.timescale;// CMTimeMake(a, b) a表示目前時間,b表示每秒鐘有多少幀 [_player seekToTime:CMTimeMakeWithSeconds(sender.value * self.sumPlayOperation, _player.currentTime.timescale) completionHandler:^(BOOL finished) { [self.player play]; }];}- (void)addNotification{ //給AVPlayerItem添加播放完成通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];}- (void)playbackFinished:(NSNotification *)notification{ NSLog(@"視頻播放完成.");}