如果设备未锁定,则音乐将在后台播放。我已将代码粘贴到 .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];
最佳答案
当设备被密码锁定时,Apple iOS 会限制数据访问。 所以你将 NSDocumetDirectory 转换为歌曲的 NSData。并分配它工作的 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];
关于ios - AVAudioPlayer 问题(如果设备被锁定,音乐文件无法在后台模式下播放),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959590/