In this example, we will show you how to use the CreativeEditor SDK’s CreativeEngine to create buffers through the editor
API. Buffers can hold arbitrary data.
public func createBuffer() -> URL
Create a resizable buffer that can hold arbitrary data.
- Returns: A URL to identify the buffer.
public func destroyBuffer(url: URL) throws
Destroy a buffer and free its resources.
url
: The URL of the buffer to destroy.
public func setBufferData(url: URL, offset: UInt, data: Data) throws
Set the data of a buffer.
url
: The URL of the buffer.offset
: The offset in bytes at which to start writing.data
: The data to write.
public func getBufferData(url: URL, offset: UInt, length: UInt) throws -> Data
Get the data of a buffer.
url
: The URL of the buffer.offset
: The offset in bytes at which to start reading.length
: The number of bytes to read.- Returns: The data read from the buffer or an error.
public func setBufferLength(url: URL, length: UInt) throws
Set the length of a buffer.
url
: The URL of the buffer.length
: The new length of the buffer in bytes.
public func getBufferLength(url: URL) throws -> NSNumber
Get the length of a buffer.
url
: The URL of the buffer.- Returns: The length of the buffer in bytes.
Full Code
Here’s the full code:
// Create an audio block and append it to the pagelet audioBlock = try engine.block.create(.audio)try engine.block.appendChild(to: page, child: audioBlock)
// Create a bufferlet audioBuffer = engine.editor.createBuffer()
// Reference the audio buffer resource from the audio blocktry engine.block.setURL(audioBlock, property: "audio/fileURI", value: audioBuffer)
// Generate 10 seconds of stereo 48 kHz audio datalet samples = ContiguousArray<Float>(unsafeUninitializedCapacity: 10 * 2 * 48000) { buffer, initializedCount in for i in stride(from: 0, to: buffer.count, by: 2) { let sample = sin((440.0 * Float(i) * Float.pi) / 48000.0) buffer[i + 0] = sample buffer[i + 1] = sample } initializedCount = buffer.count}
// Assign the audio data to the buffertry samples.withUnsafeBufferPointer { buffer intry engine.editor.setBufferData(url: audioBuffer, offset: 0, data: Data(buffer: buffer))}
// We can get subranges of the buffer datalet chunk = try engine.editor.getBufferData(url: audioBuffer, offset: 0, length: 4096)
// Get current length of the buffer in byteslet length = try engine.editor.getBufferLength(url: audioBuffer)
// Reduce the buffer to half its length, leading to 5 seconds worth of audiotry engine.editor.setBufferLength(url: audioBuffer,length: UInt(truncating: length) / 2)
// Free datatry engine.editor.destroyBuffer(url: audioBuffer)