diff --git a/ios/App/Shared/models/server/AudioTrack.swift b/ios/App/Shared/models/server/AudioTrack.swift index 8cd9e50e..f0e8f720 100644 --- a/ios/App/Shared/models/server/AudioTrack.swift +++ b/ios/App/Shared/models/server/AudioTrack.swift @@ -19,6 +19,13 @@ class AudioTrack: EmbeddedObject, Codable { @Persisted var localFileId: String? @Persisted var serverIndex: Int? + var endOffset: Double? { + if let startOffset = startOffset { + return startOffset + duration + } + return nil + } + private enum CodingKeys : String, CodingKey { case index, startOffset, duration, title, contentUrl, mimeType, metadata, localFileId, serverIndex } diff --git a/ios/App/Shared/player/AudioPlayer.swift b/ios/App/Shared/player/AudioPlayer.swift index 78b66bd9..62c185f6 100644 --- a/ios/App/Shared/player/AudioPlayer.swift +++ b/ios/App/Shared/player/AudioPlayer.swift @@ -45,7 +45,7 @@ class AudioPlayer: NSObject { internal var sleepTimer: Timer? internal var sleepTimeRemaining: Double? - private var currentTrackIndex = 0 + internal var currentTrackIndex = 0 private var allPlayerItems:[AVPlayerItem] = [] private var pausedTimer: Timer? diff --git a/ios/App/Shared/player/AudioPlayerSleepTimer.swift b/ios/App/Shared/player/AudioPlayerSleepTimer.swift index 96801559..18ad7aee 100644 --- a/ios/App/Shared/player/AudioPlayerSleepTimer.swift +++ b/ios/App/Shared/player/AudioPlayerSleepTimer.swift @@ -22,7 +22,7 @@ extension AudioPlayer { // Return the player time until sleep var sleepTimeRemaining: Double? = nil if let chapterStopAt = self.sleepTimeChapterStopAt { - sleepTimeRemaining = chapterStopAt - currentTime + sleepTimeRemaining = (chapterStopAt - currentTime) / Double(self.rate > 0 ? self.rate : 1.0) } else if self.isCountdownSleepTimerSet() { sleepTimeRemaining = self.sleepTimeRemaining } @@ -59,7 +59,22 @@ extension AudioPlayer { // Schedule the observation time self.sleepTimeChapterStopAt = stopAt - let sleepTime = CMTime(seconds: stopAt, preferredTimescale: CMTimeScale(NSEC_PER_SEC)) + + // Get the current track + guard let playbackSession = self.getPlaybackSession() else { return } + let currentTrack = playbackSession.audioTracks[currentTrackIndex] + + // Set values + guard let trackStartTime = currentTrack.startOffset else { return } + guard let trackEndTime = currentTrack.endOffset else { return } + + // Verify the stop is during the current audio track + guard trackEndTime >= stopAt else { return } + + // Schedule the observation time + let trackBasedStopTime = stopAt - trackStartTime + + let sleepTime = CMTime(seconds: trackBasedStopTime, preferredTimescale: CMTimeScale(NSEC_PER_SEC)) var times = [NSValue]() times.append(NSValue(time: sleepTime))