我正在努力开发一个应用程序,该应用程序通过逐句播放声音文件一个接一个地播放叙事。在以下代码下,它按预期播放。但是,在添加"停止"按钮以停止正在播放的内容后,我发现"停止"按钮并没有停止声音。
我在按下"播放"按钮之前测试了"停止"按钮,该按钮没有问题(打印消息)。但是,在按下"播放"并在旁白游戏播放时,"停止"按钮不起作用(没有打印消息)。
任何想法怎么了?
import UIKit
import AVFoundation
class ViewController: UIViewController,AVAudioPlayerDelegate {
var NarrationPlayer:AVAudioPlayer = AVAudioPlayer()
var soundlist: [String] = []
var counter = 0
}
func playSound(_ soundfile: String) {
let NarPath = Bundle.main.path(forResource: soundfile, ofType:"mp3")!
let NarUrl = URL(fileURLWithPath: NarPath)
do {
NarrationPlayer = try AVAudioPlayer(contentsOf: NarUrl)
NarrationPlayer.delegate = self
} catch{
print(error)
}
NarrationPlayer.play()
}
@IBAction func play(_ sender: Any) {
soundlist.append("a")
soundlist.append("b")
soundlist.append("c")
playSound("first")
while counter < soundlist.count{
if NarrationPlayer.isPlaying == true{
}
else{
playSound(soundlist[counter])
counter += 1
}
}
}
@IBAction func StopPlay(_ sender: Any) {
print("stop button worked")
}
您遇到的问题是此行:
while counter < soundlist.count{
正在携带主线程,保持任何"停止播放"按钮的任何点击。
您已经设置了一个委托方法,并且您可以在这里做的非常方便的事情之一就是增加计数器并每次播放声音文件完成时播放下一个声音文件。
类似的东西:
func playSound(_ soundfile: String) {
let NarPath = Bundle.main.path(forResource: soundfile, ofType:"mp3")!
let NarUrl = URL(fileURLWithPath: NarPath)
do {
NarrationPlayer = try AVAudioPlayer(contentsOf: NarUrl)
NarrationPlayer.delegate = self
} catch{
print(error)
}
NarrationPlayer.play()
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
{
playSound(self.soundlist[counter])
counter += 1
}
@IBAction func play(_ sender: Any) {
playSound("first")
soundlist.append("a")
soundlist.append("b")
soundlist.append("c")
}
最后一个建议:
将NarrationPlayer
的名称更改为narrationPlayer
。像Objective-C一样,Swift中的变量应从小写(也称为LowerCamelCase)开始。