在按钮点击swift 4上生成随机声音



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

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

您可以使用arc4random_uuniform((和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)
}
}

每当用户按下按钮时,运行以下代码:

在swift 4.2中,它很简单:

let sound = arrayOfSounds.randomElement()

在早期版本中:

let randIndex = Int(arc4random_uniform(20)) // Random number between 0 and 20
let sound = arrayOfSounds[randIndex]

然后使用AVAudioPlayer或您想要的任何其他方法(如制作游戏时使用SpriteKit(播放声音。

这里有一个简单的解决方案:按下按钮时调用的playSound()函数

import Foundation
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
//generate a random Int between 0 and 19, and then add 1
let random = Int(arc4random_uniform(20)) + 1
//Construct the sound file name
let randomSoundName = "sound" + String(random) + ".wav"
//Then check that the file is in the app bundle
guard let url = Bundle.main.url(forResource: randomSoundName, withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)

/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeWAVE) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}

最新更新