Swift:无法根据数组播放每个声音序列
Posted
技术标签:
【中文标题】Swift:无法根据数组播放每个声音序列【英文标题】:Swift: Unable to play each sound sequence based on array 【发布时间】:2018-04-29 00:51:50 【问题描述】:我一直在试图弄清楚如何使用 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()
【问题讨论】:
【参考方案1】:在开始下一个声音之前,您需要等待每个声音完成播放。让你的班级采用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()
【讨论】:
我在发布之前测试了这段代码,它会按顺序播放每个声音。您确定您完全按照代码进行操作吗? 在audioPlayerDidFinishPlaying
函数中添加print("in audioPlayerDidFinishPlaying")
行,以确保它被命中。
妈妈咪呀,对不起@vacawama,我的错,我没有删除案例代码 func 位因此问题的原因。现在都在工作。你是最好的。只有一个问题,如何让它播放得快?
要使其播放速度提高一倍:在audioPlayer.play()
之前添加audioPlayer.enableRate = true
audioPlayer.rate = 2.0
。您可以在0.5
(半速)到2.0
(两倍速)之间调整rate
。以上是关于Swift:无法根据数组播放每个声音序列的主要内容,如果未能解决你的问题,请参考以下文章