iPhone應(yīng)用輕松使用AVAudioPlayer音頻播放
iPhone應(yīng)用輕松使用AVAudioPlayer音頻播放是本文要介紹的內(nèi)容,iPhone SDK中的AVFoundation框架包括的AVAudioPlayer是一個容易使用而且功能強大,基于Object-c的播放音頻文件播放器。本教程展示了怎樣使用AVAudioPlayer。本教程將建立一個簡單的程序,它能夠循環(huán)播放一段mp3音頻文件。
源代碼/Guithub
教程的源代碼在GitHub上。你可以從倉庫中克隆或直接下載zip文件。
創(chuàng)建項目
- Launch Xcode and create a new View-Based iPhone application called AudioPlayer:
啟動Xcode并創(chuàng)建一個“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”將出現(xiàn)在“Linked Libraries”下,關(guān)閉窗口
下面,我們將引入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…”
找到并選擇要導(dǎo)入的音頻文件,按“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初始化的,所以我們首先要創(chuàng)立一個指向資源文件夾中音頻文件的URL。將音頻播放器的numberOfLoops屬性設(shè)為負數(shù)使得播放無限循環(huán)。配置好音頻播放器后,我們向播放器對象發(fā)送播放消息來啟動播放。
記住在dealloc方法中釋放audioPlayer。改變見粗體部分:
- - (void)dealloc
- [audioPlayer release];
- [super dealloc];
- }
更多功能
你可以調(diào)節(jié)播放器音量,查看/設(shè)定播放的時間,暫?;蛲V共シ牛?/p>
- 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
最后,你還可以實現(xiàn)AVAudioPlayer Delegate協(xié)議,比如說,在音頻播放結(jié)束時得到通知,這樣你有可能移動到播放列表的下一首歌。
小結(jié):iPhone應(yīng)用輕松使用AVAudioPlayer音頻播放的內(nèi)容介紹完了,希望本文對你有所幫助。