问题
There is an app called IHeartRadio which lets you set a sleep timer which will shut off audio after a specified interval.
You first choose a station to listen to and then select an amount of time to sleep after which the radio station will stop playing. The app does not need to be in the foreground for this to happen.
How is it possible for an app to stop audio while it is in the background?
One theory was to set a UILocalNotification with silent audio. Then the UILocalNotification would take over the audio of the device, in effect silencing whatever audio was playing. That didn't work.
Timers don't work in the background, which doesn't leave much in terms of time-based behavior in the background.
回答1:
When the UIBackgroundModes key contains the audio value, the system’s media frameworks automatically prevent the corresponding app from being suspended when it moves to the background. As long as it is playing audio or video content, the app continues to run in the background. However, if the app stops playing the audio or video, the system suspends it.
From iOS App Programming Guide.
回答2:
You can use applicationDidEnterBackground
event in your AppDelegate
to handle application going to background and stop audio in this method.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
// add your audio stopping code ..
}
来源:https://stackoverflow.com/questions/15935905/stop-audio-while-in-background