สวิฟต์ 4
import UIKit
import AudioToolbox
class ViewController: UIViewController{
var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7]
override func viewDidLoad() {
super.viewDidLoad()
for index in 0...sounds.count-1 {
let fileName : String = "note\(sounds[index])"
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index])
}
}
}
@IBAction func notePressed(_ sender: UIButton) {
switch sender.tag {
case 1:
AudioServicesPlaySystemSound(sounds[0])
case 2:
AudioServicesPlaySystemSound(sounds[1])
case 3:
AudioServicesPlaySystemSound(sounds[2])
case 4:
AudioServicesPlaySystemSound(sounds[3])
case 5:
AudioServicesPlaySystemSound(sounds[4])
case 6:
AudioServicesPlaySystemSound(sounds[5])
default:
AudioServicesPlaySystemSound(sounds[6])
}
}
}
หรือ
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func notePressed(_ sender: UIButton) {
let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
}