iOS Swift: Sound not playing

后端 未结 1 1726
死守一世寂寞
死守一世寂寞 2020-12-21 10:40

In my iOS Swift application, and i am trying to play sound on click of a button.

func playSound()
    {
        var audioPlayer = AVAudioPlayer()
        let         


        
相关标签:
1条回答
  • 2020-12-21 11:08

    You just need to move the declaration of your audioPlayer out of your method. Try like this:

    Swift 3 or later

    var audioPlayer = AVAudioPlayer()
    
    func playSound() throws {
        let url = Bundle.main.url(forResource: "doorbell", withExtension: "mp3")!
        audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
    

    do { 
        try playSound() 
    } catch { 
        print(error)
    }
    
    0 讨论(0)
提交回复
热议问题