Search code examples
iosobjective-cavaudioplayer

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


How can I save time when audio was stopped in session and continue playback from the stop point in next session?

My code:

- (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];
}

Solution

  • You can use AVPlayer's currentTime property. It returns the playback time of the current AVPlayerItem.

    To restore the playback time in the next session, you can pass the stored time to AVPlayer's 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

    To persist the CMTime returned by currentTime, you can use the AVFoundation convenience methods provided by NSValue.

    To wrap CMTime in an NSValue, use valueWithCMTime:

    [NSValue valueWithCMTime:player.currentTime];
    

    To get an CMTime struct from the persisted value, use:

    CMTime persistedTime = [storeValue CMTimeValue];
    

    After you wrapped the CMTime struct in a NSValue instance, you can use keyed archiver & NSData to write the time to disk.

    NSHipster has a good article about that topic:http://nshipster.com/nscoding/