首页 > 解决方案 > 在按钮单击时生成随机声音 swift 4

问题描述

我有一个 .wav 文件列表,从 sound1.wav、sound2.wav、sound3.wav.... 到 sound20.wav

我想在用户触摸按钮时播放随机声音。我应该使用什么方法以及如何使用?

标签: iosswift

解决方案


您可以使用 arc4random_uniform() 和 AudioServicesPlaySystemSound() 方法来实现您想要的。

首先你需要import AudioToolbox

创建一个函数来生成声音并在@IBAction函数内部调用它

这就是你的做法:

@IBAction func buttonPressed(_ sender: UIButton){
    playSound() //calling the function
}

    func playSound(){
    //select random number i.e sound1,sound2,sound3...sound[n]
    let randomNumber = Int(arc4random_uniform(TotalSoundFiles))
    //create the sound
    if let soundURL = Bundle.main.url(forResource: "sound\(randomNumber + 1)", withExtension: ".wav"){
        var mySound: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
        //Play the sound
        AudioServicesPlaySystemSound(mySound)
    }
}

推荐阅读