Swift 3 sound play

前端 未结 4 1037
我在风中等你
我在风中等你 2021-02-01 22:33

Ok I have looked into this and have tried many different ways to play a sound when a button is clicked.

How would I play a sound when a button is clicked in swift 3? I h

4条回答
  •  -上瘾入骨i
    2021-02-01 23:06

    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 :(
            }
    }
    

提交回复
热议问题