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

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

    SWIFT 4.2 / XCODE 10.1

    Note that you must call AVAudioSession.sharedInstance().setCategory() with the mode parameter in Swift 4.2.

    import AVFoundation
    
    var audioPlayer: AVAudioPlayer?
    
    func playSound() {
        if let audioPlayer = audioPlayer, audioPlayer.isPlaying { audioPlayer.stop() }
    
        guard let soundURL = Bundle.main.url(forResource: "audio_file", withExtension: "wav") else { return }
    
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default)
            try AVAudioSession.sharedInstance().setActive(true)
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            audioPlayer?.play()
        } catch let error {
            Print.detailed(error.localizedDescription)
        }
    }
    

提交回复
热议问题