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

How can I repeat a song in iOS?

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

这是我的代码 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.

您需要设置 numberOfLoops

player.numberOfLoops = 2 // or whatever 

来自 Apple 文档:

var numberOfLoops: Int

The number of times a sound will return to the beginning, upon reaching the end, to repeat playback.

对于重复歌曲,您可以将 属性 numberOfLoops 设置为 -1。它将作为无限循环工作

player.numberOfLoops = -1

使用 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()

使用 SwiftySound,只需一行代码即可完成。您所要做的就是为 numberOfLoops 参数传递 -1 值。

Sound.play(file: "dog", fileExtension: "wav", numberOfLoops: -1)

您可以在 GitHub 上找到 SwiftySound