我都设置了一个AVPlayer类,该类可以流音频文件。它有点长,所以我不能在这里发布整个内容。我坚持的是如何让用户在听完一次音频文件后重播该音频文件。第一次完成时,我正确地收到了通知AVPlayerItemDidPlayToEndTimeNotification
。当我重播它时,我立即收到相同的通知,这使我无法重播它。
我该如何重置它,以使其AVPlayerItem
不认为它已经播放了音频文件?我可以重新分配所有内容,然后重新进行设置,但是我认为这将迫使用户再次下载音频文件,这是毫无意义且缓慢的。
这是我认为相关的部分课程。尝试重播文件时得到的输出如下所示。前两行正是我所期望的,但第三行令人惊讶。
正在播放
没有计时器
音频播放器已完成播放音频
- (id) initWithURL : (NSString *) urlString
{
self = [super init];
if (self) {
self.isPlaying = NO;
self.verbose = YES;
if (self.verbose) NSLog(@"url: %@", urlString);
NSURL *url = [NSURL URLWithString:urlString];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
[self determineAudioPlayTime : self.playerItem];
self.lengthOfAudioInSeconds = @0.0f;
[self.player addObserver:self forKeyPath:@"status" options:0 context:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
}
return self;
}
// this is what gets called when the user clicks the play button after they have
// listened to the file and the AVPlayerItemDidPlayToEndTimeNotification has been received
- (void) playAgain {
[self.playerItem seekToTime:kCMTimeZero];
[self toggleState];
}
- (void) toggleState {
self.isPlaying = !self.isPlaying;
if (self.isPlaying) {
if (self.verbose) NSLog(@"is playing");
[self.player play];
if (!timer) {
NSLog(@"no timer");
CMTime audioTimer = CMTimeMake(0, 1);
[self.player seekToTime:audioTimer];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(updateProgress)
userInfo:nil
repeats:YES];
}
} else {
if (self.verbose) NSLog(@"paused");
[self.player pause];
}
}
-(void)itemDidFinishPlaying:(NSNotification *) notification {
if (self.verbose) NSLog(@"audio player has finished playing audio");
[[NSNotificationCenter defaultCenter] postNotificationName:@"audioFinished" object:self];
[timer invalidate];
timer = nil;
self.totalSecondsPlayed = [NSNumber numberWithInt:0];
self.isPlaying = NO;
}
您可以在播放机收到AVPlayerItemDidPlayToEndTimeNotification时调用seekToTime方法
func itemDidFinishPlaying() {
self.player.seek(to: CMTime.zero)
self.player.play()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句