Search code examples
iosbackground-music

How to shut down the music in background mode on IOS program?


I make a iOS program to use the AVAudioPlayer to play music on the background. But I don't know how to shut down the music after a certain time. I try to use the UILocalNotification to stop music in the method:

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notification

But the way only effectly after the user recieved the Notification and click to shut down!

How can I stop the music automatically after a certain time?


Solution

  • If you use AVPlayer instead of AVAudioPlayer you can achieve this using addBoundaryTimeObserverForTimes:queue:usingBlock:

    I have tried this with AVQueuePlayer (which is a subclass of AVPlayer) and it worked.

    Try something like this:

    id observer = [avPlayer addBoundaryTimeObserverForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:CMTimeMake(60, 1)]] queue:NULL usingBlock:^{
            [avPlayer pause];
        }];
    

    And somewhere later:

    [avPlayer removeTimeObserver:observer];