Sishu
Sishu

Reputation: 1558

want to keep AVPlayer playing when application goes to background

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.

Upvotes: 1

Views: 5246

Answers (4)

Nitin Gohel
Nitin Gohel

Reputation: 49730

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>

Upvotes: 8

Iya
Iya

Reputation: 1918

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;
}

Upvotes: 7

zadr
zadr

Reputation: 2525

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.

Upvotes: 3

jcm
jcm

Reputation: 1789

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

Upvotes: 2

Related Questions