在 Swift 中重复播放声音文件?



我通过按下按钮,使用以下代码成功地播放了声音。但是,我想按下一个按钮,让该声音循环/无限播放。这是如何实现的?我还想实现暂停/播放功能。提前谢谢。

@IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
}


func playSound(soundName: String) { 
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
} 
// End of Play Sound

默认情况下,AVAudioPlayer从头到尾播放其音频然后停止播放,但我们可以通过设置其numberOfLoops属性来控制使其循环的次数。例如,要使您的音频总共播放三次,您可以编写以下内容:

player.numberOfLoops = 3

如果你想要无限循环,那么使用

player.numberOfLoops =  -1  

例如

func playSound(soundName: String) { //
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.numberOfLoops =  -1 // set your count here 
player.play()
} // End of Play Sound

var audioPlayer: AVAudioPlayer?

func startBackgroundMusic() {
if let bundle = Bundle.main.path(forResource: "Guru_Nanak_Sahib_Ji", ofType: "mp3") {
let backgroundMusic = NSURL(fileURLWithPath: bundle)
do {
audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
guard let audioPlayer = audioPlayer else { return }
audioPlayer.numberOfLoops = -1 // for infinite times
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}

您可以留住玩家。 然后在玩家的完成委托回调中,再次开始播放。 或者随时停止播放器,因为您保留了对它的引用。

最新更新