Mercurial > public > geoquiz
diff GeoQuiz/Logic/Game.swift @ 5:f31a61462e7a
add sound effects
author | Dennis C. M. <dennis@denniscm.com> |
---|---|
date | Sat, 24 Sep 2022 12:02:09 +0100 |
parents | de54f05adb78 |
children | 1946bbfde4af |
line wrap: on
line diff
--- a/GeoQuiz/Logic/Game.swift Thu Sep 22 11:38:42 2022 +0200 +++ b/GeoQuiz/Logic/Game.swift Sat Sep 24 12:02:09 2022 +0100 @@ -7,6 +7,7 @@ import Foundation import SwiftUI +import AVFAudio protocol Game: ObservableObject { @@ -40,6 +41,9 @@ // Modal views var showingBuyLivesView: Bool { get set } var showingGameStatsView: Bool { get set } + + // Sound effects + var player: AVAudioPlayer? { get set } } extension Game { @@ -95,6 +99,7 @@ if correctAnswer == choice { hapticSuccess() + play("correctAnswer") withAnimation(.easeIn(duration: 0.5)) { scoreScaleAmount += 1 @@ -105,7 +110,7 @@ askQuestion() } else { hapticError() - + play("wrongAnswer") withAnimation(.easeIn(duration: 0.5)) { livesScaleAmount += 1 @@ -126,4 +131,24 @@ } } } + + private func play(_ filename: String) { + guard let soundFileURL = Bundle.main.url(forResource: filename, withExtension: "wav") else { + fatalError("Sound file \(filename) couldn't be found") + } + + do { + try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient) + try AVAudioSession.sharedInstance().setActive(true) + } catch { + fatalError("Couldn't activate session") + } + + do { + player = try AVAudioPlayer(contentsOf: soundFileURL) + player?.play() + } catch { + fatalError("Couldn't play sound effect") + } + } }