Swift 3声音播放

sha*_*ane 16 avfoundation avaudioplayer swift3

好的我已经调查了这个并且在点击按钮时尝试了许多不同的方式播放声音.

在swift 3中单击按钮时如何播放声音?我的声音名为Sounds,名称为ClickSound.mp3

Ami*_*wat 18

用户低于此功能

 //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)
    }
}
Run Code Online (Sandbox Code Playgroud)

首先导入AudioToolbox导入AVFoundation

希望它有效:)

  • var player:AVAudioPlayer?将其声明为全球性的. (2认同)

Amr*_*tfy 14

您必须防止玩家被处置,将其置于视图控制器的属性中

唯一真正的问题是,您必须将您的播放器存储为不会立即销毁的属性或其他变量 - 如果不这样做,声音将立即停止.

资源:

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 :(
        }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 5

您可能想要使用SwiftySound.它可以让你在Swift 3和Swift 4中轻松播放声音.

Sound.play(file: "ClickSound.mp3")
Run Code Online (Sandbox Code Playgroud)