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

前端 未结 6 827
一整个雨季
一整个雨季 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:20

    A very simple solution.

    import AVFoundation
    
    var myAudioPlayer = AVAudioPlayer?
    
    func playAudioFile() {
    
        let audioFileURL = Bundle.main.url(forResource: "", withExtension: "mp3/wav/m4a etc.")
    
        do {
            try myAudioPlayer = AVAudioPlayer(contentsOf: audioFileURL!)
        } catch let error {
            print(error.localizedDescription)
        }
    
        myAudioPlayer?.play()
    
    }
    

    Now, play this audio file anywhere by calling: playAudioFile()

提交回复
热议问题