简体   繁体   中英

AVPlayer — Observing rate to toggle play/pause buttons

I'm using AVPlayer and I'm simply trying to toggle my play/pause button correctly. I can't just toggle based on user action because I'm starting/stopping the player automatically at times.

So I'm observing the rate key of the AVPlayer, and when a notification is sent, I check the rate .

  • If 0, then I show the "play" button. (Player is paused)
  • If 1, then I show the "pause" button. (Player is playing)

This works perfectly except for one situation. When the app goes to background and then becomes active again, the rate first goes to "1" and then to "0". So the button goes from "pause" to "play".

However, the video keeps playing, but I never get another rate notification of "1".

I even added this to code block that observes rate :

[self performSelector:@selector(logRate) withObject:nil afterDelay:3.0];

I'm just checking the rate again 3 seconds after the last "0" rate change was observed. The video is still playing but the rate is still "0".


Does anyone know either: 1. Why this would happen? 2. Is there a better way to observe if an AVPlayer is playing or paused besides rate ?

I don't know exactly why this is happening but I did find an isolated fix that also might help someone more knowledgeable figure this out.

I discovered that if I "paused" the player before going to background, when I went to foreground and resumed "play" I never got the rate going from "1" to "0". It went to "1" and stayed there.

So for my case I just added an observation for:

  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(willResignActive:) name:UIApplicationWillResignActiveNotification object:nil];

and I now pause the player in willResignActive: .


What this does tell me is that going to background while the AVPlayer is playing puts the AVPlayer in a state that caused the error I asked about, but I don't know any further details right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM