AVPlayer + loop + background
I need to:
- play a sound
- loop
- continue to play in b开发者_运维问答ackground
All works fine with AVAudioPlayer
, but now I have to use AVPlayer
to play also music songs from the iPod library. But there is a big problem: AVPlayer has no numberOfLoops
property like in AVAudioPlayer
.
Ok, you can register a notification to the NSNotificationCenter
for AVPlayerItemDidPlayToEndTimeNotification
(or you can also use the addBoundaryTimeObserverForTimes
method with specified times equal to the song duration) to be notified when a song has played to the end.
But this works only if the app is in the foreground, in the background the song continues to play, but stops at the end.
The notification is received also in the background (checked with a NSLog), but the selector's code:
AVPlayerItem *playerItem = [notification object];
[playerItem seekToTime:kCMTimeZero];
...has no effect, the song doesn't loop.
Any suggestions?
The problem you have is the second the player does a seektotime your app looks like it's done playing audio, and so it's thrown on the bonfire. :)
I spent days creating this workaround:
Add "App plays audio" to "Required background mode" in info.plist
Create another AVplayer that plays a one second mp3 file at 0.00000001f rate (silentMp3Player.rate=0.0000001f) which starts when your app enters background and stops when it re-enters foreground.
Try to add this code:
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
精彩评论