A few bug fixes

- Only set durations if we have successfully loaded
audio data.

- Use weak self in the completion handler so we clean up
properly.

- Handle cases where there are no utterances in a document

- When a user selects to download audio, force overwrite
the cached data.
This commit is contained in:
Jackson Harper 2022-09-20 21:57:48 +08:00
parent 8c71c0b384
commit a23760a296
2 changed files with 15 additions and 8 deletions

View file

@ -78,17 +78,20 @@ class SpeechPlayerItem: AVPlayerItem {
resourceLoaderDelegate.owner = self
self.observer = observe(\.status, options: [.new]) { item, _ in
item.session.updateDuration(forItem: item.speechItem, newDuration: CMTimeGetSeconds(item.duration))
if item.status == .readyToPlay {
let duration = CMTimeGetSeconds(item.duration)
item.session.updateDuration(forItem: item.speechItem, newDuration: duration)
}
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self, queue: OperationQueue.main) { _ in
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self, queue: OperationQueue.main) { [weak self] _ in
guard let self = self else { return }
self.completed()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
removeObserver(self, forKeyPath: "status")
observer = nil
resourceLoaderDelegate.session?.invalidateAndCancel()
}
@ -136,7 +139,6 @@ class SpeechPlayerItem: AVPlayerItem {
}
// TODO: how do we want to propogate this and handle it in the player
// The exception is just from some old code and does nothing.
let audioData = try? await SpeechSynthesizer.download(speechItem: speechItem, session: self.session)
DispatchQueue.main.async {
self.mediaData = audioData
@ -281,7 +283,7 @@ public class AudioController: NSObject, ObservableObject, AVAudioPlayerDelegate
let synthesizer = SpeechSynthesizer(appEnvironment: appEnvironment, networker: networker, document: document)
for item in synthesizer.createPlayerItems(from: 0) {
do {
_ = try await SpeechSynthesizer.download(speechItem: item)
_ = try await SpeechSynthesizer.download(speechItem: item, redownloadCached: true)
} catch {
print("error downloading audio segment: ", error)
return false
@ -525,6 +527,9 @@ public class AudioController: NSObject, ObservableObject, AVAudioPlayerDelegate
setupRemoteControl()
}
}
if items.count < 1 {
state = .reachedEnd
}
}
}

View file

@ -79,8 +79,10 @@ struct SpeechSynthesizer {
}
func preload() async throws {
if let item = speechItemForIdx(idx: 0) {
_ = try await Self.download(speechItem: item)
if document.utterances.count > 0 {
if let item = speechItemForIdx(idx: 0) {
_ = try await Self.download(speechItem: item)
}
}
}