后台播放音乐

来源:互联网 发布:linux密码修改 编辑:程序博客网 时间:2024/06/06 10:44

当退出程序的时候,在后台可以继续播放

#import "ViewController.h"#import <AVFoundation/AVFoundation.h>@interface ViewController (){    AVAudioPlayer* player;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    dispatch_async(dispatch_get_global_queue(0, 0), ^{       //设置可以后台播放音乐,音频会话对象        AVAudioSession* session=[AVAudioSession sharedInstance];        if ([session setCategory:AVAudioSessionCategoryPlayback error:nil]) {            NSLog(@"后台播放设置成功");        }else            NSLog(@"后台播放设置失败");        //播放音乐        NSString* filePath=[[NSBundle mainBundle]pathForResource:@"像梦一样自由" ofType:@"mp3"];        NSData* data=[NSData dataWithContentsOfFile:filePath];        player=[[AVAudioPlayer alloc]initWithData:data error:nil];        if (player!=nil) {            if ([player prepareToPlay]) {                [player play];            }        }    });}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end
原创粉丝点击