ios - AVAudioPlayer 问题(如果设备被锁定,音乐文件无法在后台模式下播放)

标签 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];

最佳答案

当设备被密码锁定时,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/

相关文章:

ios - 在 UIKit 中为图像添加阴影

iphone - Apple 推送通知注册和设备 token 收到说明?

ios - 固定背景图像 PhoneGap/类固醇?

audio - ios声音不再在应用程序中起作用(仅在设备上)

ios - 录音看起来没问题,但播放却不行

ios - 停止调用后从头开始播放AvAudioPlayer文件

php - 网站、API 和 iPhone 应用程序让用户通过 Facebook 登录

iOS:如何制作多列表

html - AngularJS:一个 index.html 中的注册和内容页面

html - 使用 chrome 滚动时背景无法正确加载