1。必须导入
#import <AVFoundation/AVFoundation.h>
2。实现协议: <AVAudioPlayerDelegate>
e.g.
@property (nonatomic, strong)AVAudioPlayer *audioPlayer;
- (void)actionPlay {
//为后续异步加载,使用并行全局队列
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//加载本地音频资源 bundle -> file -> data ,因为有可能音频文件比较大,所以采用异步加载
dispatch_async(dispatchQueue, ^(void) {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
/* 当模拟器有声音,真机无声音时 需在启动播放器之前 加上以下这一句 */
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
/* 初始化 音频播放器 */
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
if (self.audioPlayer != nil){
/* 设置代理,启动 */
self.audioPlayer.delegate = self;
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing");
} else {
NSLog(@"Failed to play");
}
} else {
NSLog(@"Failed to instantiate AVAudioPlayer");
}
});
}
//可在结束播放时,释放(无论是正常停止,或是意外停止) 参数flag : 播放是否成功结束
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(@"Finished playing the song");
if ([player isEqual:self.audioPlayer]){
self.audioPlayer = nil;
} else {
/* 其它播放器不作处理 */
}
}
//被中断,如来电等
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
/* Audio Session is interrupted. The player will be paused here */
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionOptionShouldResume && player != nil){
[player play];
}
}