IOS后台运行音频文件

首先在配置文件中打开后台运行音频,如上图。

下一步在代码中添加

//设置后台播放

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

    [audioSession setActive:YES error:nil];

//添加远程控制事件

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

//播放录音, tempStr是项目中添加进来的音频文件名

    NSError *error;

    NSURL *tempURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle]pathForResource:tempStr ofType:@"mp3"]];

//创建一个全局播放器对象player,注意一定要是全局的对象,在这里初始化。

    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:tempURL

                                                     error:&err];

//清空URL

    tempURL = nil;

    //对播放器属性进行设置

    _player.volume = 0.8;

    _player.currentTime = 0.0;

    _player.delegate = self;

    [_player prepareToPlay];

    

    [_player play];

//最后在dealloc中移除远程控制事件

 [[UIApplication sharedApplication] endReceivingRemoteControlEvents];

posted on 2016-09-20 16:09  Rao-Joyce  阅读(293)  评论(0)    收藏  举报

导航