1. AVFoundation
Build Phases => Link Binary With Libraies => + => AVFoundation.framework => add
firstviewcontroller.h
#import <UIKit/UIKit.h>#import <AVFoundation/AVFoundation.h>@interface FirstViewController : UIViewController{ __weak IBOutlet UILabel *label; AVAudioPlayer *player;}- (IBAction)toplay:(id)sender;@end
firstviewcontroller.m
- (IBAction)toplay:(id)sender { NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]]]; NSError *error; player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; player.numberOfLoops = -1; [player play]; [label setText:@"Play ..."];}
或者:
NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]; NSError *error; player = [[AVAudioPlayer alloc]initWithContentsOfURL:[[NSURL alloc]initFileURLWithPath:path]error:&error]; [player prepareToPlay];player.numberOfLoops = -1;[player play];
test.mp3 拖放到 Supporting Files 文件夾。
播放,暫停和停止
[player play]; //播放[player pause]; //暫停[player stop]; //停止
更多功能:
1. 音量:
player.volume=0.8;//0.0~1.0之間
2. 循環次數
player.numberOfLoops = 3;//默認只播放一次 負數(-1)為無限循環
3.播放位置
player.currentTime = 15.0;//可以指定從任意位置開始播放
3.1 顯示當前時間
NSLog(@"%f seconds played so far", player.currentTime);
4.聲道數
NSUInteger channels = player.numberOfChannels;//只讀屬性
5.持續時間
NSTimeInterval duration = player.dueration;//獲取采樣的持續時間
6.儀表計數
player.meteringEnabled = YES;//開啟儀表計數功能[ player updateMeters];//更新儀表讀數//讀取每個聲道的平均電平和峰值電平,代表每個聲道的分貝數,范圍在-100~0之間。for(int i = 0; i<player.numberOfChannels;i++){float power = [player averagePowerForChannel:i];float peak = [player peakPowerForChannel:i];}
7. 初始化播放器
[player prepareToPlay];
8. 判斷是否正在播放
[player isPlaying]
9、代理方法
加入播放出現異常,或者被更高級別的系統任務打斷,我們的程序還沒來得及收場就掛了,怎么辦?不急,我們可以通過幾個委托方法很好地處理所有的情形。
首先給player設置委托是必須的:
player.delegate = self;
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{ //播放結束時執行的動作}- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{ //解碼錯誤執行的動作}- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{ //處理中斷的代碼}- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{ //處理中斷結束的代碼}
參考:
http://blog.csdn.net/xys289187120/article/details/6595919
http://blog.csdn.net/iukey/article/details/7295962
視頻:
http://www.youtube.com/watch?v=kCpw6ip90cY
2. AudioToolbox
Build Phases => Link Binary With Libraies => + => AudioToolbox.framework => add
firstviewcontroller.h
#import <UIKit/UIKit.h>#import <AudioToolbox/AudioToolbox.h>@interface FirstViewController : UIViewController{ }- (IBAction)toplay:(id)sender;@end
firstviewcontroller.m
- (IBAction)toplay:(id)sender{ CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef soundFileURLRef; soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"sound1", CFSTR ("wav"), NULL); UInt32 soundID; AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); AudioServicesPlaySystemSound(soundID);}
視頻:
http://www.youtube.com/watch?v=lSJhYx28Krg&feature=youtu.be
新聞熱點
疑難解答