2

当iOS设备被锁定时,我正在做以下事情来播放音频,但它不起作用。

  1. Info.plist 文件中的 UIBackgroundModes 键(带有值音频)。
  2. 设置音频会话

代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self createAudioSession];

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"jgj" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:soundFilePath];
    NSLog(@"%@",[url path]);
    NSError* error;
    self.audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if (self.audioPlayer == nil)
        NSLog(@"%@",[error description]);
    else
    {
        self.audioPlayer.numberOfLoops=-1;
        [self.audioPlayer play];
    }

}

-(void)createAudioSession
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];

    // Use this code to allow the app sound to continue to play when the screen is locked.
    NSError* error=nil;
    BOOL ok=[audioSession setCategory: AVAudioSessionCategoryPlayback error: &error];
    if(!ok)
        NSLog(@"%@",[error description]);
    else
        NSLog(@"hello");

    ok=[audioSession setActive:YES error:&error];
    if(!ok)
        NSLog(@"%@",[error description]);
    else
        NSLog(@"world");
}
4

0 回答 0