代码之家  ›  专栏  ›  技术社区  ›  user6428350

我如何在iOS中重复一首歌?

  •  1
  • user6428350  · 技术社区  · 7 年前

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

    4 回复  |  直到 6 年前
        1
  •  4
  •   nayem    7 年前

    使用 AVAudioPlayer numberOfLoops

    Apple doc 的讨论部分:

    stop() 方法

    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()
    
        2
  •  1
  •   Anil Varghese    7 年前

    您需要设置 numberOfLoops

    player.numberOfLoops = 2 // or whatever 
    

    来自Apple doc:

    到达终点,重复播放。

        3
  •  1
  •   Lalit kumar    7 年前

    player.numberOfLoops = -1
    
        4
  •  1
  •   Adam    7 年前

    迅捷之声 ,只需一行代码即可完成。您所要做的就是为传递-1值 参数

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

    SwiftySound 在GitHub上。