iPhone應用便於使用AVAudioPlayer音頻播放是本文要介紹的內容,iPhone SDK中的AVFoundation架構套件括的AVAudioPlayer是一個容易使用而且功能強大,基於Object-c的播放音頻檔案播放器。本教程展示了怎樣使用AVAudioPlayer。本教程將建立一個簡單的程式,它能夠迴圈播放一段mp3音頻檔案。
原始碼/Guithub
教程的原始碼在GitHub上。你可以從倉庫中複製或直接下載zip檔案。
建立項目
- Launch Xcode and create a new View-Based iPhone application called AudioPlayer:
啟動Xcode並建立一個“View-Based iPhone application”項目,取名為AudioPlayer:
1.從Xcode菜單選擇“File > New Project …”
2.從“iPhone OS > Application”部分選擇“View-based Application”,然後按“Choose…”
3.將項目命名為“AudioPlayer”並按“Save”
添加AVFoundation架構
為使用SDK的AVAudioPlayer類,我們需要將AVFoundation架構加入項目:
1.在項目的“Groups & Files”面板上,展開“Targets”
2.Control+點擊或右擊AudioPlayer
3.選擇“Add > Existing Frameworks…”
4.點擊Linked Libraries下左下方的+按鈕
5.選擇“AVFoundation Framework“並按Add
6.“AVFoundation framewoks”將出現在“Linked Libraries”下,關閉視窗
下面,我們將引入AVFoundation的標頭檔
1.展開項目“Group & Files”面板下AudioPlayer項目
2.開啟Classes檔案夾
3.選取AudioPlayerViewController.h進行編輯
4.變更檔。更改以下粗體字部分:
- #import <UIKit/UIKit.h>
- #import <AVFoundation/AVFoundation.h>
-
- @interface AudioPlayerViewController : UIViewController
- {
- AVAudioPlayer *audioPlayer;
- }
- @end
添加音頻檔案
我們需要一段音頻檔案來進行播放。檔案為audiofie.mp3。我們將其加入項目中:
按Control再左擊或右擊項目的“Group & Files”面板中的“Resources”檔案夾
從操作功能表中選取“Add > Existing Files…”
找到並選擇要匯入的音頻檔案,按“Add”
有必要的話)選定“Copy items into destination group’s folder”方框並按“Add”
開始播放音頻
我們在ViewDidLoad中啟動音頻播放:
1.解除ViewDidLoad方法的註解
2.更改如下,見粗體部分:
- - (void)viewDidLoad
-
- [super viewDidLoad];
-
- NSURL *url = [NSURL fileURLWithPath:[NSString
- stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
- NSError *error;
- audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
- audioPlayer.numberOfLoops = -1;
- if (audioPlayer == nil)
- NSLog([error description]);
- else
- [audioPlayer play];
AVAudioPlayer是通過URL初始化的,所以我們首先要創立一個指向資源檔夾中音頻檔案的URL。將音頻播放器的numberOfLoops屬性設為負數使得播放無限迴圈。配置好音頻播放器後,我們向播放器對象發送播放訊息來啟動播放。
記住在dealloc方法中釋放audioPlayer。改變見粗體部分:
- - (void)dealloc
-
- [audioPlayer release];
- [super dealloc];
- }
更多功能
你可以調節播放器音量,查看/設定播放的時間,暫停或停止播放:
- audioPlayer.volume = 0.5; // 0.0 - no volume; 1.0 full volume
- NSLog(@"%f seconds played so far", audioPlayer.currentTime);
- audioPlayer.currentTime = 10; // jump to the 10 second mark
- [audioPlayer pause];
- [audioPlayer stop]; // Does not reset currentTime; sending play resumes
最後,你還可以實現AVAudioPlayer Delegate協議,比如說,在音頻播放結束時得到通知,這樣你有可能移動到播放清單的下一首歌。
小結:iPhone應用便於使用AVAudioPlayer音頻播放的內容介紹完了,希望本文對你有所協助。