我一直试图弄清楚如何使用switch case语句基于数组中的值来播放一系列声音。到目前为止它只播放相应声音的最后一个整数。
我希望实现的是当我单击“播放”按钮时,它会循环播放每个soundSeq数组值并在停止之前播放相应的声音。但在这种情况下,它只播放tagid 5的声音。
import UIKit
import AVFoundation
class UIController: UIViewController {
var audioPlayer : AVAudioPlayer!
let soundSeq = [2,4,5]
func playSoundSeq() {
for tag in soundSeq {
switch tag {
case 1 : loopSoundSeq(tagid: tag)
case 2 : loopSoundSeq(tagid: tag)
case 3 : loopSoundSeq(tagid: tag)
case 4 : loopSoundSeq(tagid: tag)
case 5 : loopSoundSeq(tagid: tag)
case 6 : loopSoundSeq(tagid: tag)
case 7 : loopSoundSeq(tagid: tag)
default : print("no sound played")
}
}
}
@IBAction func playButton(_ sender: UIButton) {
playSoundSeq()
}
func loopSoundSeq(tagid: Int) {
var soundURl = Bundle.main.url(forResource: "minisound\(tagid)", withExtension: "wav")
//machinePlay.append(sender.tag)
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURl!)
}
catch {
print(soundURl)
}
audioPlayer.play()
}
}
答案 0 :(得分:2)
在开始下一个声音之前,您需要等待每个声音完成播放。让您的班级采用AVAudioPlayerDelegate
并实施AVAudioPlayerDelegate
方法audioPlayerDidFinishPlaying(_:successfully:)
并触发序列中的下一个声音:
import UIKit
import AVFoundation
class UIController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer!
let soundSeq = [2, 4, 5]
var index = 0
func playSoundSeq() {
if index < soundSeq.count {
loopSoundSeq(tagid: soundSeq[index])
index += 1
}
}
@IBAction func playButton(_ sender: UIButton) {
index = 0
playSoundSeq()
}
func loopSoundSeq(tagid: Int) {
let soundURL = Bundle.main.url(forResource: "minisound\(tagid)", withExtension: "wav")!
//machinePlay.append(sender.tag)
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
audioPlayer.delegate = self
}
catch {
print(soundURL)
}
audioPlayer.play()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag {
playSoundSeq()
}
}
}