【问题标题】:AVAudioPlayer will not play when device is locked设备锁定时,AVAudioPlayer 不会播放
【发布时间】:2011-06-29 07:10:46
【问题描述】:

我在我的应用程序中使用AVAudioPlayer。当我选择它播放的歌曲时,但我的问题是,当设备被锁定时它没有播放。

【问题讨论】:

  • 你的问题解决了吗?请告诉我..我也面临同样的问题..

标签: objective-c ios cocoa-touch avaudioplayer


【解决方案1】:

您需要阅读 Apple 文档中的 Executing Code in the Background。如果您将应用程序的Info.plist 中的UIBackgroundModes 键设置为audio,音频将在后台播放时继续播放。

请参阅上述文档中的声明您支持的后台任务播放后台音频部分。

【讨论】:

    【解决方案2】:

    我们只需要通过两步使用 AVAudioPlayer 在后台播放音乐:

    第 1 步:选择项目 -> 功能 -> 启用背景模式 -> 选择音频模式

    第 2 步:使用此代码:

    NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"demo" withExtension:@"mp3"];
    avSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
    [avSound setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [avSound prepareToPlay];
    [avSound setNumberOfLoops:-1];
    [avSound setVolume:1.0]; 
    

    请注意,即使应用程序在后台,音乐也可以开始播放:

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    

    【讨论】:

    • beginReceivingRemoteControlEvents 真的成功了!你知道使用它是否有一些限制吗?谢谢!!
    【解决方案3】:

    据我所知,设备锁定时无法播放声音。在用户手动关闭设备之前,您不能只禁止设备锁定和激活应用程序吗?

    【讨论】:

    • 很多闹钟在被锁定很长时间后确实会启动音频。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多