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

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

    SWIFT 4 / XCODE 9.1

    import AVFoundation
    
    var objPlayer: AVAudioPlayer?
    
    func playAudioFile() {
        guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
    
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
    
            // For iOS 11 
            objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
    
            // For iOS versions < 11 
            objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) 
    
            guard let aPlayer = objPlayer else { return }
            aPlayer.play()
    
        } catch let error {
            print(error.localizedDescription)
        }
    }
    

提交回复
热议问题