Question

I have one sound file which is playing continuosly in application. What I want is when my app goes in background my audio file should pause and when my app comes in foreground my audio file should start playing . What scenario I want is if my audio file is of 4 min and it is playing and at current it is played of 2 min then app goes in background for 1 min then my audio file should now start playing from that 3 min play not from 2 min at which it was paused. I don't want to use background mode of capabilities. Is there any other way to accomplish this? My code is as below:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath],soundFile]];

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    audioPlayer.numberOfLoops =-1;
    audioPlayer.volume=0.5f;


    if (audioPlayer == nil)
        NSLog(@"error playing file.");
    else
        [audioPlayer play];
Was it helpful?

Solution

Step 1

When your application go to background or goes to inactive state, you need to save the current playback time.

You can get the currentTime by using currentTime property of AVAudioPlayer

You can save the value to NSUserDefaults for persistence

You can use the following delegate to detect the application inactive state

- (void)applicationWillResignActive:(UIApplication *)application

Step 2

When your come active, you can retrieve the data from the NSUserDefaults and using that you can play it from the time where your music stopped.

For detecting the state, you need to use:

- (void)applicationDidBecomeActive:(UIApplication *)application

You can set the currentTime property for restarting the playing from the position where you stopped it.

OTHER TIPS

Take audioPlayer object at global. when your app goes to background then add below code In AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
     [audioPlayer pause];
} 

When your comes in background then add below code in AppDelegate.m

- (void)applicationWillEnterForeground:(UIApplication *)application
{
     [audioPlayer play];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top