停止AVPlayer并重新启动MP3文件。

25
我希望能够开始、暂停和停止(相当于重新启动)我的mp3文件,并且我正在使用AVPlayer,这些文件是从服务器获取的。
要开始播放歌曲,我需要执行以下操作:
[self.player start];

我要暂停时,我会:

[self.player pause];
但是当我想停止这首歌并重新加载它,以便下一次用户点击“开始按钮”时从开头开始播放时,我不知道该怎么做。 我尝试了类似以下的东西:
[self.player pause];
self.player = nil;

但是此时播放器已经为空,我没有办法在不重新初始化的情况下重新启动文件。有什么方法可以停止它吗?


2
[self.player seekToTime:CMTimeMakeWithSeconds(0, 5) completionHandler:nil] 可以让视频从头开始播放。 - Sandeep
非常完美,像魔法一样运行。非常感谢! - Davis
@Sandeep,第二个参数(5)是干什么用的? - user5306470
6个回答

50

使用[player pause]停止视频播放

然后在开始视频时使用此代码。

[player seekToTime:kCMTimeZero];
[player play];

我更喜欢这个比解决 OP 的评论,因为它消除了警告并使用一个常数。


20

最好的解决方法是在Swift 4之前:

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

Swift >= 4:

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

2
  • 在 Xamarin.ios 中

player.Seek(CoreMedia.CMTime.Zero);

player.Play();


2

seek#to具有完成处理程序。

p?.seek(to: .zero)
p?.rate = 1

这并不是完全正确的。你可能会遇到音频抖动

p?.seek(to: .zero) { [weak self] _ in
    self?.p?.rate = 1
}

这可能是你想要的。

如果它已经在播放,并且你只是进行搜索而没有其他操作,那么也可能会出现卡顿。

最好的方法可能是:

p?.rate = 0
p?.seek(to: .zero) { [weak self] _ in
    self?.p?.rate = 1
}

如果这是一个非常重要的应用程序,您还需要考虑寻求完成的错误情况。

1
在Swift 4中:self.player.seek(to: CMTime.zero)


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

由于糟糕的代码格式和缺乏解释,这个答案并不有帮助。 - Kerem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接