gpt4 book ai didi

ios - 重播 AVPlayerItem/AVPlayer 无需重新下载

转载 作者:技术小花猫 更新时间:2023-10-29 11:00:42 26 4
gpt4 key购买 nike

我有一个 AVPlayer 类,全部设置为流式传输音频文件。它有点长,所以我不能在这里发布整个内容。我坚持的是如何让用户在听完一次音频文件后重播。当它第一次完成时,我正确地收到通知 AVPlayerItemDidPlayToEndTimeNotification。当我去重播它时,我立即收到相同的通知,这阻止了我重播它。

我怎样才能重置它,使 AVPlayerItem 不认为它已经播放了音频文件?我可以取消分配所有内容并重新设置,但我相信这会迫使用户再次下载音频文件,这是毫无意义且缓慢的。

以下是类(class)中我认为相关的部分内容。我尝试重放文件时得到的输出如下所示。前两行正是我所期望的,但第三行是一个惊喜。

is playing
no timer
audio player has finished playing audio

- (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()
}

关于ios - 重播 AVPlayerItem/AVPlayer 无需重新下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27812809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com