2011-12-12 89 views
1

我试图在应用移动到背景时播放声音。iPhone:当应用移动到背景时播放声音

- (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中,它正在播放声音,但主屏幕上有一个红色条表示应用程序在后台仍处于活动状态。其实这并不是我想要的。我只想要播放声音,并且我不需要应用程序始终处于活动状态。

有没有解决这个问题的方法?

回答

0

我不认为你可以这样做,因为当你的应用程序被推到背景时,你正在产生的所有音频将被静音。

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

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

在代码中添加这三行: -

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