gpt4 book ai didi

ios - 如何在 iOS 中重复播放一首歌曲?

转载 作者:行者123 更新时间:2023-11-28 21:05:28 25 4
gpt4 key购买 nike

我正在尝试在我的应用中重复播放一首歌曲。但是,它只是播放到最后,然后完全停止。我如何为此添加循环功能?

这是我在 viewDidLoad 中的代码:

    do
{
let audioPath = Bundle.main.path(forResource: "APP4", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)

}

catch

{

//catch error
}

let session = AVAudioSession.sharedInstance()

do
{

try session.setCategory(AVAudioSessionCategoryPlayback)

}

catch
{

}
player.play()

我正在使用 Xcode 8。

最佳答案

使用 AVAudioPlayernumberOfLoops 属性来获取重复功能。

来自Apple doc的讨论部分:

A value of 0, which is the default, means to play the sound once. Set a positive integer value to specify the number of times to return to the start and play again. For example, specifying a value of 1 results in a total of two plays of the sound. Set any negative integer value to loop the sound indefinitely until you call the stop() method.

所以使用:

player.numberOfLoops = n - 1 // here n (positive integer) denotes how many times you want to play the sound

或者,为了利用无限循环使用:

player.numberOfLoops = -1
// But somewhere in your code, you need to stop this

停止播放:

player.stop()

关于ios - 如何在 iOS 中重复播放一首歌曲?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45912830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com