Ios 在Swift 5中播放我的项目中的随机声音
我是iOS新手。我编写了这段代码,当点击UIButton时,它只播放一个音频文件。我想随机播放多个声音。如何设置?谢谢大家!Ios 在Swift 5中播放我的项目中的随机声音,ios,swift,avfoundation,avaudioplayer,Ios,Swift,Avfoundation,Avaudioplayer,我是iOS新手。我编写了这段代码,当点击UIButton时,它只播放一个音频文件。我想随机播放多个声音。如何设置?谢谢大家! import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer: AVAudioPlayer! @IBAction func playButtonPressed(_ sender: UIButton) { if
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
@IBAction func playButtonPressed(_ sender: UIButton) {
if let soundURL = Bundle.main.url(forResource: "kompilacja", withExtension: "mp3") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}else{
print("Karwasz twarz! Brak pliku audio, Panie!")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
将所有声音文件名放在一个数组中,并使用randomElement方法选择声音
@IBAction func playButtonPressed(_ sender: UIButton) {
let sounds = ["kompilacja", "another sound", "yet another sound"]
guard let sound = sounds.randomElement(),
let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}
将所有声音文件名放在一个数组中,并使用randomElement方法选择声音
@IBAction func playButtonPressed(_ sender: UIButton) {
let sounds = ["kompilacja", "another sound", "yet another sound"]
guard let sound = sounds.randomElement(),
let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}
他不想播放一个随机的声音。他想随机播放多个声音他不想播放一个随机的声音。他想随机播放多个声音