24

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Davis
  • 1,253
  • 4
  • 17
  • 38

6 Answers6

49

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.

Cbas
  • 6,003
  • 11
  • 56
  • 87
18

Best solution to do this in Swift < 4:

player.seek(to: kCMTimeZero)
player.play()

Swift >= 4:

player.seek(to: .zero)
player.play()
Community
  • 1
  • 1
fabioalmeida
  • 336
  • 4
  • 7
2
  • In Xamarin.ios

player.Seek(CoreMedia.CMTime.Zero);

player.Play();

Kamalkumar.E
  • 254
  • 2
  • 11
2

seek#to has a completion handler.

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.

Community
  • 1
  • 1
Fattie
  • 27,874
  • 70
  • 431
  • 719
1

In Swift 4: self.player.seek(to: CMTime.zero)

Reefwing
  • 2,242
  • 1
  • 22
  • 23
-1
// 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];
  }
Ramani Hitesh
  • 214
  • 3
  • 15