How to play a sound on iOS 11 with swift 4? And where i place The mp3 file?

前端 未结 6 815
一整个雨季
一整个雨季 2021-01-03 07:47

I saw a lot of tutorials but when i click button (that actvivate The func playsound) The sound doesn’t play. I saw the code reccomended by stackoverflow but nothing. I put

6条回答
  •  独厮守ぢ
    2021-01-03 08:22

    Simple way with Swift 4.2:

    import AVFoundation
    

    and

       let soundEffect = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
       var audioPlayer = AVAudioPlayer()
    
       @IBAction func buttonClick(sender: AnyObject) {
           do {
                audioPlayer = try AVAudioPlayer(contentsOf: soundEffect)
                audioPlayer.play()
           } catch {
              // couldn't load file :(
           } 
       }
    

提交回复
热议问题