【问题标题】:iPhone: Play sound when app moves to backgroundiPhone:当应用程序移至后台时播放声音
【发布时间】:2011-12-12 10:57:29
【问题描述】:

我正在尝试在应用移至后台时播放声音。

- (void)applicationWillResignActive:(UIApplication *)application
{   
    NSError *error;
    NSURL *goodByeSoundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"GoodBye" ofType:@"wav"]];
    AVAudioPlayer *goodByeSound = [[AVAudioPlayer alloc] initWithContentsOfURL:goodByeSoundUrl error:&error];
    [goodByeSound play];
}

此代码不适用于我的设备(带有 iOS 5.0 的 iPhone 4)。但它确实适用于模拟器。 如果我将以下行添加到 Info.plist 中,它正在播放声音,但主屏幕上有一个红色条,表示应用程序在后台仍处于活动状态。

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

其实这不是我想要的。我只想播放声音,我不需要应用程序一直在后台运行。

这个问题有解决办法吗?

【问题讨论】:

    标签: iphone audio background avaudioplayer


    【解决方案1】:

    在你的代码中添加这三行:-

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        【解决方案3】:

        我认为你不能这样做,因为当你的应用被推到后台时,你正在制作的所有音频都会被静音。

        添加背景模式将不起作用,因为这仅适用于音频播放器。

        <key>UIBackgroundModes</key>
        <array>
            <string>audio</string>
        </array>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-11
          • 2018-02-04
          • 2011-08-15
          相关资源
          最近更新 更多