📜  scheduleBuffer(audioFileBuffer, atTime: nil, options:.Loops (1)

📅  最后修改于: 2023-12-03 14:47:17.989000             🧑  作者: Mango

ScheduleBuffer Method

Introduction

The ScheduleBuffer method is a part of the AVAudioPlayerNode class in the AVFoundation framework. This method schedules the playback of an audio file buffer at a specified point in time on the audio node's timeline. It can also be set to loop the audio file buffer, so that it plays continuously until stopped.

Syntax
func scheduleBuffer(_ buffer: AVAudioPCMBuffer,
                    atTime when: AVAudioTime?,
                    options: AVAudioPlayerNodeBufferOptions = [])
Parameters
  • buffer: An instance of the AVAudioPCMBuffer class that contains the audio data to be scheduled for playback.
  • when: An instance of the AVAudioTime class that specifies the time at which the audio data should begin playback. If this parameter is nil, the buffer will be scheduled to play immediately.
  • options: An optional value of the AVAudioPlayerNodeBufferOptions enum, which allows you to set options for the buffer playback. The default value is an empty array.
Return Value

This method does not return a value.

Example
let audioFileURL = Bundle.main.url(forResource: "myAudioFile", withExtension: "wav")
let audioFile = try! AVAudioFile(forReading: audioFileURL!)
let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: AVAudioFrameCount(audioFile.length))
try! audioFile.read(into: audioFileBuffer!)

let playerNode = AVAudioPlayerNode()
audioEngine.attach(playerNode)
audioEngine.connect(playerNode, to: audioEngine.outputNode, format: audioFileBuffer.format)

playerNode.scheduleBuffer(audioFileBuffer, atTime: nil, options: .loops)

try! audioEngine.start()

playerNode.play()

In the example above, we first create an instance of an AVAudioFile object from an audio file in the app bundle, and then read the contents of the file into an AVAudioPCMBuffer object. We then create an instance of the AVAudioPlayerNode class, attach it to the audio engine, and connect it to the output node. Finally, we use the scheduleBuffer method to schedule the playback of the audio file buffer on the player node, immediately after the engine has started running. The buffer is set to loop continuously until stopped.