我已经设置好了一个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;
}