Question

I have to play a mp3 file using avplayer ,but when i go to background it stops ,How do i keep it playing in background state as well.Any advise will be highly appreciated. Thanks.

Was it helpful?

Solution

in to your plist fine just add one method like:-

enter image description here

Or in code:

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

OTHER TIPS

To play AVPlayer in background,you have to follow below steps:

1) to add "Required background modes" property in info.plist,with value "App plays audio or streams audio/video using AirPlay"

2)to import below in AppDelegate.h file:

 #import <AVFoundation/AVFoundation.h>
 #import <AudioToolbox/AudioToolbox.h>

3)in your AppDelegate.m ,
application didFinishLaunchingWithOptions this exactly like below:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
// Override point for customization after application launch.

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

return YES;
}

You should read Technical Q&A 1668, Playing media while in the background using AV Foundation on iOS. In it, Apple gives examples of how to play media in the background with AVPlayer, as well as discusses potential issues you may run into.

From the docs I posted in the comment:

An app that plays or records audio continuously (even while the app is running in the background) can register to perform those tasks in the background. You enable audio support from the Background modes section of the Capabilities tab in your Xcode project. (You can also enable this support by including the UIBackgroundModes key with the audio value in your app’s Info.plist file.) Apps that play audio content in the background must play audible content and not silence.

...

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 or recording audio content, the app continues to run in the background. However, if recording or playback stops, the system suspends the app.

App States and Multitasking Guide

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top