I want to start, pause and stop (same as restart) my mp3 File and I'm using AVPlayer. I get the files from a server.
To start the song I do:
[self.player start];
To pause I do:
[self.player pause];
but when I want to stop the song and reload it, so that the song starts from the beginning when the User clicks on the "start button" next time, I have no idea what to do.
I tried something like this:
[self.player pause];
self.player = nil;
But then the player is nil of course and I can't restart the file again without a new initialization. Any ideas how to stop it?
Stop the video using [player pause]
Then use this code when you start the video.
[player seekToTime:kCMTimeZero];
[player play];
I like this better than the comment that solved the OP it b/c it eliminates a warning and uses a constant.
Best solution to do this in Swift < 4:
player.seek(to: kCMTimeZero)
player.play()
Swift >= 4:
player.seek(to: .zero)
player.play()
player.Seek(CoreMedia.CMTime.Zero);
player.Play();
p?.seek(to: .zero)
p?.rate = 1
is not really correct. You can get audio jitter .
p?.seek(to: .zero) { [weak self] _ in
self?.p?.rate = 1
}
is probably what you want.
If it is already playing , and you just do the seek and nothing else, again you could get the jitters.
You are probably best to
p?.rate = 0
p?.seek(to: .zero) { [weak self] _ in
self?.p?.rate = 1
}
If it's a really important app, you'll also have to consider the error condition in the seek completion.
在 Swift 4: self.player.seek(to: CMTime.zero)
// If conti. play Video or audio apply this code
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd
:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[avPlayer currentItem]];
[avPlayer play];
- (void)playerItemDidReachEnd:(NSNotification *)notification
{
NSLog(@"Replay video in method");
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}
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.