Swift 3 sound play

瘦欲@ 提交于 2019-12-03 05:54:48

问题


Ok I have looked into this and have tried many different ways to play a sound when a button is clicked.

How would I play a sound when a button is clicked in swift 3? I have my sound in a folder named Sounds and the name is ClickSound.mp3


回答1:


User below this function

 //MARK:- PLAY SOUND
func playSound() {
    let url = Bundle.main.url(forResource: "ClickSound", withExtension: "mp3")!

    do {
        player = try AVAudioPlayer(contentsOf: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()
    } catch let error as NSError {
        print(error.description)
    }
}

first import AudioToolbox import AVFoundation

Hope it works :)




回答2:


You have to keep the player from being disposed of, get it in a property of your view controller

The only real catch is that you must store your player as a property or other variable that won't get destroyed straight away – if you don't, the sound will stop immediately.

source:

var player : AVAudioPlayer?

func playSound(){
        let path = Bundle.main.path(forResource: "alert", ofType:"mp3")!
        let url = URL(fileURLWithPath: path)

        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            self.player = sound
            sound.numberOfLoops = 1
            sound.prepareToPlay()
            sound.play()
        } catch {
            print("error loading file")
            // couldn't load file :(
        }
}



回答3:


You might want to use SwiftySound. It lets you play sounds easily in Swift 3 and Swift 4.

Sound.play(file: "ClickSound.mp3")



回答4:


A much easier way to do this is to put the following line of code in your button pressed function (Note: Only works in sprite kit):

run(SKAction.playSoundFileNamed("ClickSound.mp3", waitForCompletion: false))

Hope this helps :)



来源:https://stackoverflow.com/questions/40602114/swift-3-sound-play

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!