前提:选中项目-设置-Capabilities-Background Modes-Audio and AirPlay 勾选中
#import <AVFoundation/AVFoundation.h>
protocol:<AVAudioPlayerDelegate>
e.g.
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
/* Audio Session is interrupted. The player will be paused here */
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
withOptions:(NSUInteger)flags{
/* Check the flags, if we can resume the audio, then we should do it here */
if (flags == AVAudioSessionInterruptionOptionShouldResume){
[player play];
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(@"Finished playing the song");
/* flag:successfully finished or not */
if ([player isEqual:self.audioPlayer]){
self.audioPlayer = nil;
} else {
/* This isn't our audio player! */
}
}
-(void)actionPlay {
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:YES error:nil];
if ([audioSession setCategory:AVAudioSessionCategoryPlayback
error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
}
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *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 {
/* AVAudioPlayer 初始化失败 */
}
});
}