如何在 Xcode10 中循环 AvAudioPlayerNode

how to loop AvAudioPlayerNode in Xcode10

你好,我正在 SpriteKit 中制作一个 iOS 游戏,并决定使用 AvAudioPlayerNode 和引擎而不是常规的 AvAudioPlayer,这样我就可以改变音调和播放速度,但我遇到了一个问题,其中 AvAudioPlayerNode播放后不重复

我已经使用了很多来自堆栈溢出的答案,但是如果你碰巧解决了这个问题,它们已经过时了,你能确保它适用于我的代码,否则它就没用了

//

let engine = AVAudioEngine()
let speedControl = AVAudioUnitVarispeed()
let pitchControl = AVAudioUnitTimePitch()
let audioplayer = AVAudioPlayerNode()
let audioPath = Bundle.main.path(forResource: "loop", ofType: "wav")


func play(_ url: URL) throws {

 let file = try AVAudioFile(forReading: url)



 engine.attach(audioplayer)
 engine.attach(pitchControl)
 engine.attach(speedControl)

 engine.connect(audioplayer, to: speedControl, format: nil)
 engine.connect(speedControl, to: pitchControl, format: nil)
 engine.connect(pitchControl, to: engine.mainMixerNode, format: nil)

 audioplayer.scheduleFile(file, at: nil)

 try engine.start()
 audioplayer.play()


}

'

//这只是通过这样做

在游戏视图控制器中得到运行
let audioPath = Bundle.main.path(forResource: "loop", ofType: "wav") ?? ""

    do
    {

        try? play(URL(fileURLWithPath: audioPath))
    }
    catch {
}

我实际上不知道从哪里开始我是 Xcode 的新手所以任何帮助都会有用,请不要把事情复杂化我是 15

您想将文件读入缓冲区,然后安排播放器循环播放

let file = try AVAudioFile(forReading: url)
let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: file.fileFormat, frameCapacity: file.length)
try? read(into buffer: audioFileBuffer )
audioFilePlayer.scheduleBuffer(audioFileBuffer, atTime: nil, options:.Loops, completionHandler: nil)
audioFilePlayer.play()