如何保存音频文件的位置? objective-C

How to save the position of the audio file? objective -C

如何在会话中停止音频时节省时间并在下一个会话中从停止点继续播放?

我的代码:

- (void)initPlayer:(NSString*) audioFile fileExtension:(NSString*)fileExtension
{

NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:audioFile withExtension:fileExtension];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];

if ([audioFile isEqualToString:@"2"]) {
    _index = 1;
}
else if ([audioFile isEqualToString:@"3"]) {
    _index = 2;
}

[self song];

}
- (void)playAudio {
[self.audioPlayer play];


}

- (void)pauseAudio {
[self.audioPlayer pause];

}
- (BOOL)isPlaying {
return [self.audioPlayer isPlaying];
}
-(NSString*)timeFormat:(float)value{

float minutes = floor(lroundf(value)/60);
float seconds = lroundf(value) - (minutes * 60);

int roundedSeconds = lroundf(seconds);
int roundedMinutes = lroundf(minutes);

NSString *time = [[NSString alloc]
                  initWithFormat:@"%d:%02d",
                  roundedMinutes, roundedSeconds];
return time;
}
- (void)setCurrentAudioTime:(float)value {
[self.audioPlayer setCurrentTime:value];
}
- (NSTimeInterval)getCurrentAudioTime {
return [self.audioPlayer currentTime];
}
- (float)getAudioDuration {
return [self.audioPlayer duration];
}

最简单的方法是用歌曲名称保存一个本地数据库,当它停止时将该数据添加到数据库中。然后当回放稍后恢复时,首先检查本地数据库是否有任何过去的条目。如果不从头继续。

还要确保歌曲播放完毕后没有输入。

希望这个想法对你有帮助...

您可以使用 AVPlayer 的 currentTime 属性。它returns当前AVPlayerItem的播放时间。

下次会话恢复播放时间,可以将存储的时间传给AVPlayer的seekToTime:

[self.player seekToTime:storedPlaybackTime];

https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVPlayer_Class/index.html#//apple_ref/doc/uid/TP40009530-CH1-SW2

https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVPlayer_Class/index.html#//apple_ref/occ/instm/AVPlayer/seekToTime%3a

要持久化 currentTime 返回的 CMTime,可以使用 NSValue 提供的 AVFoundation 便捷方法。

要将 CMTime 包装在 NSValue 中,请使用 valueWithCMTime:

[NSValue valueWithCMTime:player.currentTime];

要从持久值中获取 CMTime 结构,请使用:

CMTime persistedTime = [storeValue CMTimeValue];

将 CMTime 结构包装在 NSValue 实例中后,您可以使用键控存档器和 NSData 将时间写入磁盘。

NSHipster 有一篇关于该主题的好文章:http://nshipster.com/nscoding/