Swift 3 sound play
User below this function
//MARK:- PLAY SOUND
func playSound() {
let url = Bundle.main.url(forResource: "ClickSound", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
first import AudioToolbox import AVFoundation
Hope it works :)
You have to keep the player from being disposed of, get it in a property of your view controller
The only real catch is that you must store your player as a property or other variable that won't get destroyed straight away – if you don't, the sound will stop immediately.
source:
var player : AVAudioPlayer?
func playSound(){
let path = Bundle.main.path(forResource: "alert", ofType:"mp3")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
self.player = sound
sound.numberOfLoops = 1
sound.prepareToPlay()
sound.play()
} catch {
print("error loading file")
// couldn't load file :(
}
}
You might want to use SwiftySound. It lets you play sounds easily in Swift.
Sound.play(file: "ClickSound.mp3")