ios - 在按钮单击时生成随机声音 swift 4
问题描述
我有一个 .wav 文件列表,从 sound1.wav、sound2.wav、sound3.wav.... 到 sound20.wav
我想在用户触摸按钮时播放随机声音。我应该使用什么方法以及如何使用?
解决方案
您可以使用 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)
}
}
推荐阅读
- sql - 如何使用 tSQL 根据条件定义 EventStop 时间戳?
- spring-boot - 我实现了具有管理员和客户的 api 列表的客户服务
- git - Github 部署密钥允许我克隆多个私有存储库
- java - 如何在同一个 Android 应用程序中使用 Navigation Drawer 和 Bottom Navigation
- snakemake - snakemake中的“只能将输入文件指定为函数”
- sql-server - Schema Compare 和 SqlPackage 150 区分大小写问题
- python - 如何修复 Debian-RaspberryPi3 上损坏的 apt-listchanges?
- shell - Shell 运行 StreamSets 管道
- apache-kafka - Flink 流未完成
- bash - bash 参数扩展中的内联命令替换