我正在開發一個應用程序,通過一個接一個地播放逐句語音文件來播放旁白。 使用下面的代碼,它按預期播放。但是,添加「停止」按鈕停止正在播放的內容後,我發現「停止」按鈕沒有停止聲音。AVAudioPlayer在播放時不會停止
我測試了「停止」按鈕,然後按下「播放」按鈕,這沒有任何問題(消息已打印)。但是,在按下「播放」並且正在播放NarrationPlayer時,「停止」按鈕不起作用(沒有消息被打印)。
任何想法有什麼不對?
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")
}
我不知道它是否相關,但爲什麼在變量計數器 – 3stud1ant3
@ 3stud1ant3之後出現閉括號,因爲有一個開放式支架{{爲其各自的類 –