Skip to content

Instantly share code, notes, and snippets.

@WLun001
Last active May 20, 2018 05:15
Show Gist options
  • Save WLun001/d0206624e0f9863efcce9493111c9569 to your computer and use it in GitHub Desktop.
Save WLun001/d0206624e0f9863efcce9493111c9569 to your computer and use it in GitHub Desktop.
iOS 11 Swift 4 Play sound
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer: AVAudioPlayer!
@IBAction func notePressed(_ sender: UIButton) {
playSound("note\(sender.tag)")
}
func playSound(_ soundFile: String) {
let soundURL = Bundle.main.url(forResource: soundFile, withExtension: "wav")
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error.localizedDescription)
}
audioPlayer.play()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment