How can we handle enable/disable background audio abilities at runtime on iOS devices?
Asked Answered
O

2

0

I know how to set up my iOS application to make it playing audio in background (= when another application is used on the iOS device) using the plist.

Some applications like: - BLOOM - some radio players

provides a basic UISwitch to enable or disable this behavior.

Any ideas about how to do that ?

Overexert answered 8/5, 2012 at 18:37 Comment(0)
I
5

Have an iVar of type UIBackgroundTaskIdentifier in the main class that handles audio playing code, initialize this with beginBackgroundTaskWithExpirationHandler.... method before starting the audio player and use endBackgroundTask when audio player completes.

Code:

@inerface AudioPlayerController : NSObject
{
    UIBackgroundTaskIdentifier bgTaskID;
}
@end

@implementation AudioPlayerController

- (void) startPlayer
{

    bgTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

   // Write code to start the audio player
}

// Call this when your program receives message of audio playing complete

- (void) audioPlayComplete
{

    // Do the audio playing finish

    if (bgTaskID != UIBackgroundTaskInvalid)
      [[UIApplication sharedApplication] endBackgroundTask:bgTaskID];
} 

@end
Inheritrix answered 8/5, 2012 at 19:24 Comment(2)
I'll test that. But it doesn't answer to the UISwitch which would enable or disable this background feature. I mean: the user want to use the app as an audio player for background, he enables it. He doesn't want, he disables it and in that case, when he switches to another application, no more audio play in the background.Overexert
The above code is to demonstrate how we can do the background audio play programatically. Enabling or disabling using UISwitch can be achieved by taking yet another BOOL iVar and writing the code for background task conditionally.Inheritrix
S
0

In your AppDeletate:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[YouPlayerClass sharedInstance] stop];
}

Thus The audio stops at app entering background.

Skyla answered 14/3, 2014 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.