-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundManager.swift
More file actions
54 lines (45 loc) · 1.41 KB
/
SoundManager.swift
File metadata and controls
54 lines (45 loc) · 1.41 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//
// SoundManager.swift
// Swothie
//
// Created by Passavee Losripat on 20/2/2567 BE.
//
import AVFoundation
class BackgroundMusicManager {
static let shared = BackgroundMusicManager()
private var musicPlayer1: AVAudioPlayer?
private var musicPlayer2: AVAudioPlayer?
init() {
setupAudioPlayer(&musicPlayer1, fileName: "level0", fileType: "mp3")
setupAudioPlayer(&musicPlayer2, fileName: "EpicBGM", fileType: "mp3")
}
private func setupAudioPlayer(_ player: inout AVAudioPlayer?, fileName: String, fileType: String) {
guard let url = Bundle.main.url(forResource: fileName, withExtension: fileType) else {
print("\(fileName).\(fileType) not found.")
return
}
do {
player = try AVAudioPlayer(contentsOf: url)
player?.numberOfLoops = -1
player?.prepareToPlay()
} catch {
print("Failed to initialize AVAudioPlayer for \(fileName): \(error)")
}
}
func playMusic(musicNumber: Int) {
switch musicNumber {
case 1:
musicPlayer2?.stop()
musicPlayer1?.play()
case 2:
musicPlayer1?.stop()
musicPlayer2?.play()
default:
print("Invalid music number.")
}
}
func stopMusic() {
musicPlayer1?.stop()
musicPlayer2?.stop()
}
}