AVAudioPlayer问题(如果设备被锁定,音乐文件不以后台模式播放)

时间:2013-11-13 16:48:01

标签: ios background avaudioplayer

如果设备没有锁定,那么音乐正在后台播放。我已将代码粘贴到.Plist文件中,这里是我使用过的代码

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:saveFileName];
    NSURL *url1 = [[NSURL alloc] initFileURLWithPath: path];
    appdelegate.sharedplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:NULL];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    [appdelegate.sharedplayer setVolume:appdelegate.volumeDelegate];

    [appdelegate.sharedplayer play];

3 个答案:

答案 0 :(得分:3)

当设备锁定密码时,Apple iOS会限制数据访问。 所以你将NSDocumetDirectory转换为歌曲的NSData的arry。并指定AVAudioPlayer工作。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:saveFileName];
NSURL *url1 = [[NSURL alloc] initFileURLWithPath: path];
NSData *data=[[NSData alloc]initWithContentsOfURL:url1];
appdelegate.sharedplayer=[[AVAudioPlayer alloc] initWithData:data error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[appdelegate.sharedplayer setVolume:appdelegate.volumeDelegate];
[appdelegate.sharedplayer play];

答案 1 :(得分:-1)

您需要在plist文件中进行一些更改。

a-set您的应用不在后台运行 b-将背景模式设置为App播放音频

AppDelege

中使用此代码
NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
    [[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

答案 2 :(得分:-1)

尝试在project.plist

中设置此项

set this in your plist