-
Notifications
You must be signed in to change notification settings - Fork 0
/
AudioManager.swift
39 lines (33 loc) · 1019 Bytes
/
AudioManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import SwiftUI
import AVFoundation
class AudioManager: ObservableObject {
static let shared = AudioManager()
var audioPlayer: AVAudioPlayer?
@Published var isMuted: Bool = false {
didSet {
audioPlayer?.volume = isMuted ? 0 : 1
}
}
private init() {
setupBackgroundMusic()
}
func setupBackgroundMusic() {
if let path = Bundle.main.path(forResource: "Storytelling-Essentials-Free-No-Copyright-Music-by-Liborio-Conti-01-Cinematic-Piano", ofType: ".mp3") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.numberOfLoops = -1
audioPlayer?.prepareToPlay()
} catch {
print("Error setting up background music")
}
}
}
func playBackgroundMusic() {
if !isMuted {
audioPlayer?.play()
}
}
func toggleMute() {
isMuted.toggle()
}
}