Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Audio interruption crash fix #26

Merged
merged 1 commit into from
Oct 27, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Sources/SwiftFortuneWheel/Utils/Audio/AudioPlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@ class AudioPlayer {
let node = AVAudioPlayerNode()
/// Audio player state
var state: State = State.idle()
/// Current interruption state
private(set) var isAudioInterrupted = false

init() {
NotificationCenter.default.addObserver(self,
selector: #selector(handleInterruption),
name: AVAudioSession.interruptionNotification,
object: AVAudioSession.sharedInstance())
}

/// Stops audio when interrupted
@objc private func handleInterruption(notification: Notification) {
guard let userInfo = notification.userInfo,
let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
return
}

isAudioInterrupted = type == .began

if isAudioInterrupted {
node.stop()
}
}

/// Plays `AVAudioFile` for sound identifier
/// - Parameters:
Expand All @@ -30,6 +54,9 @@ class AudioPlayer {
self?.didCompletePlayback(for: identifier)
}
}

guard !isAudioInterrupted else { return }

state = State(sound: identifier, status: .playing)
node.play()
}
Expand Down