Skip to content

Instantly share code, notes, and snippets.

@pyxn
Created April 20, 2020 12:22
Show Gist options
  • Save pyxn/a7c4237c14c6a983b56624d32f32bf6a to your computer and use it in GitHub Desktop.
Save pyxn/a7c4237c14c6a983b56624d32f32bf6a to your computer and use it in GitHub Desktop.
A reusable sound model created for the SwiftUI framework.
import SwiftUI
import AVFoundation
class Sound {
var audioPlayer: AVAudioPlayer?
func soundSetup() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
try AVAudioSession.sharedInstance().setActive(true)
} catch
let error as NSError {
print(error)
}
}
func play(sound: String, type: String) {
soundSetup()
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.play()
} catch {
print("Could not find and play the sound file.")
}
}
}
func clear() {
play(sound: "clear", type: "wav")
}
func activate() {
play(sound: "activate", type: "wav")
}
func deploy() {
play(sound: "deploy", type: "wav")
}
func step() {
play(sound: "step", type: "wav")
}
func block() {
play(sound: "block", type: "wav")
}
func recalibrate() {
play(sound: "recalibrate", type: "wav")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment