使用AVAudioPlayer/Slider/Button及UITextView來實作一個AudioPlayer
1. 先開一個專案
2. 將一個UITextView拉到storyBoard,裡面會有一些基本文字,將其換成歌詞
3. 再將一個Button及Slider拉過來使用,將Button也加上文字 ,這裡使用大悲咒
4. 將大悲咒的MP3加入到專案中
5. 將AVFoundation Framework加入到專案內,在Builder Phase下有一個加號,按入就會顯示選擇的視窗
6. 在選擇視窗下,加入一個搜尋字AV,就會出現AVFoundation Framework,選擇加入。
7. 元件註冊到audioPlayerViewController.h,並加入AVFoundation.h及AVAudioPlayer的變數,參考圖中文字
8. 將Button及Slider從StoryBoard中拉出IBAction到audioPlayerViewController.m,並加上所需的程式碼
#import "audioPlayerViewController.h"
@interface audioPlayerViewController ()
@end
@implementation audioPlayerViewController
@synthesize textDisplay;
@synthesize playButton;
@synthesize soundSlider;
@synthesize audioPlayer;
int clicked = 0;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setTextDisplay:nil];
[self setPlayButton:nil];
[self setSoundSlider:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)playAction:(id)sender {
if (clicked == 0) {
clicked = 1;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/大悲咒(齊豫).mp3", [[NSBundle mainBundle] resourcePath]]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
audioPlayer.numberOfLoops = 0;
//[audioPlayer play];
//[url release];
[audioPlayer play];
[playButton setTitle:@"大悲咒(齊豫):停止" forState:UIControlStateNormal];
//[url release];
}
else {
[audioPlayer pause];
clicked = 0;
[playButton setTitle:@"大悲咒(齊豫):播放" forState:UIControlStateNormal];
}
}
- (IBAction)voiceChange:(id)sender {
audioPlayer.volume = soundSlider.value;
}
@end
9.完成後,就可聽到歌聲了,參考執行結果圖








