【发布时间】:2015-03-04 22:55:34
【问题描述】:
我有一个 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 通过后,您无法重播该项目。我目前的解决方法是创建一个新的 Item+Player 但这只是重新下载整个东西
-
@eyeballz - 不。目前,我只是释放它,然后重新实例化。几乎不是一个好的解决方案,但这是我目前能做的最好的。如果你有什么发现,请发帖。
-
好的,我让它为我工作,但它的视频不是音频。视频的问题似乎是您还必须保留 PlayerLayer,但您在任何地方都没有那种用于音频的层。
标签: ios objective-c audio avplayer avplayeritem