0

嗨,我正在 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 岁的事情过于复杂

4

1 回答 1

2

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

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()
于 2019-09-05T19:57:41.743 回答