-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViewController.swift
77 lines (65 loc) · 2.54 KB
/
ViewController.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import UIKit
import AVFoundation
class ViewController: UIViewController {
var bgmPlayer: AVAudioPlayer?
var sePlayer: AVAudioPlayer?
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func playSound(player: AVAudioPlayer) {
guard player.prepareToPlay() else { return }
player.volume = 1.0
player.play()
}
func audioURL(name: String) -> NSURL {
let filePath = NSBundle.mainBundle().pathForResource(name, ofType: "mp3")
return NSURL(fileURLWithPath: filePath!)
}
func playBGM(name: String) {
do {
bgmPlayer = try AVAudioPlayer(contentsOfURL: audioURL(name))
bgmPlayer?.numberOfLoops = -1
playSound(bgmPlayer!)
} catch { print("Error") }
}
func playSE(name: String) {
do {
sePlayer = try AVAudioPlayer(contentsOfURL: audioURL(name))
sePlayer?.numberOfLoops = 0
playSound(sePlayer!)
} catch { print("Error") }
}
func volumeDown(player: AVAudioPlayer, _ downVolume: Float, _ downInterval: Double) {
while player.volume > downVolume {
player.volume -= downVolume
NSThread.sleepForTimeInterval(downInterval)
}
}
@IBAction func fadeout(sender: AnyObject) {
guard let player = bgmPlayer else { return }
guard player.playing else { return }
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {
self.volumeDown(player, 0.1, 0.3)
self.volumeDown(player, 0.01, 0.1)
self.volumeDown(player, 0.001, 0.05)
player.stop()
})
}
@IBAction func stopSound(sender: AnyObject) {
if let player = bgmPlayer { player.stop() }
}
@IBAction func halfSound(sender: AnyObject) {
if let player = bgmPlayer { player.volume = 0.5 }
}
@IBAction func maxSound(sender: AnyObject) {
if let player = bgmPlayer { player.volume = 1.0 }
}
@IBAction func playOpening(sender: AnyObject) { playBGM("opening") }
@IBAction func playClosing(sender: AnyObject) { playBGM("closing") }
@IBAction func playThinking(sender: AnyObject) { playBGM("thinking") }
@IBAction func playSpecial(sender: AnyObject) { playBGM("special") }
@IBAction func playQuiz(sender: AnyObject) { playSE("quiz") }
@IBAction func playCorrect(sender: AnyObject) { playSE("correct") }
@IBAction func playInCorrect(sender: AnyObject) { playSE("incorrect") }
}