Question

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?

Was it helpful?

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

OTHER TIPS

I would love to be proved wrong, but I believe that what you're asking to do might be impossible. My impression is that if the user actually clicks the Home button to send your app into the background, it can't function as a "sleep timer", because you can't run a timer. Apple's own apps can do this sort of thing, but they have special privileges.

For example, look at this app:

https://itunes.apple.com/us/app/music-sleep-timer/id320583424?mt=8

Look at how he says, "Remember to keep this app in the foreground!" Clearly that's because once the app is background, the timer stops working.

You might be better off advising the user to resort to the countdown timer in Apple's Clock app. It can shut down your music and put the device to sleep.

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