Search Docs
Loading...
Skip to content

For Audio Processing

Export audio from pages, video blocks, audio blocks, and tracks to WAV, MP4 or WebM format for external processing, transcription, or analysis.

The exportAudio API allows you to extract audio from any block that contains audio content. This is particularly useful when integrating with external audio processing services like speech-to-text transcription, audio enhancement, or music analysis platforms.

Audio can be exported from multiple block types:

  • Page blocks - Export the complete mixed audio timeline
  • Video blocks - Extract audio tracks from videos
  • Audio blocks - Export standalone audio content
  • Track blocks - Export audio from specific timeline tracks

Export Audio#

Export audio from any block using the exportAudio API:

guard let page = try engine.scene.getCurrentPage() else { return }
var audioData = Data()
for try await event in try await engine.block.exportAudio(
page,
mimeType: .wav,
options: AudioExportOptions(timeOffset: 0, duration: 10)
) {
switch event {
case let .progress(_, encodedFrames, totalFrames):
print("Encoded \(encodedFrames) of \(totalFrames) frames")
case let .finished(audio):
audioData = audio
}
}
print("Exported \(audioData.count) bytes")

exportAudio returns a stream of events: progress reports, then the finished file. Cancel the task that iterates the stream to stop the export.

Export Options#

Choose the file type with mimeType:

  • .wav - Uncompressed audio. This is the default.
  • .mp4Audio - Compressed AAC audio. .mp4 is the video type, which an audio export rejects.
  • .webmAudio - Compressed Opus audio.

Configure the rest with AudioExportOptions:

  • timeOffset - Start time in seconds. The default is 0.
  • duration - Length to export in seconds. The default, 0, exports the whole block.
  • sampleRate and numberOfChannels - The export writes 48000 Hz stereo. Another value fails the export.
  • audioCodec - The codec of an MP4 or WebM file. .auto picks AAC for MP4 and Opus for WebM.

Find Audio Sources#

To find blocks with audio in your scene:

// Find audio blocks
let audioBlocks = try engine.block.find(byType: .audio)
// Find video fills with audio
let videoFills = try engine.block.find(byType: FillType.video)
var videosWithAudio: [DesignBlockID] = []
for videoFill in videoFills {
// The track count needs the loaded video, and a fill without a file has no tracks to load.
try? await engine.block.forceLoadAVResource(videoFill)
if let trackCount = try? engine.block.getAudioTrackCountFromVideo(videoFill), trackCount > 0 {
videosWithAudio.append(videoFill)
}
}

Working with Multi-Track Video Audio#

Videos can contain multiple audio tracks (e.g., different languages). CE.SDK provides APIs to inspect and extract specific tracks.

Check audio track count#

guard let videoFillId = try engine.block.find(byType: FillType.video).first else { return }
let trackCount = try engine.block.getAudioTrackCountFromVideo(videoFillId)
print("Video has \(trackCount) audio track(s)")

Get track information#

let audioTracks = try engine.block.getAudioInfoFromVideo(videoFillId)
for (index, track) in audioTracks.enumerated() {
print("""
Track \(index):
- Channels: \(track.channels) // 1=mono, 2=stereo
- Sample Rate: \(track.sampleRate) Hz
- Language: \(track.language.isEmpty ? "unknown" : track.language)
- Label: \(track.trackName.isEmpty ? "Track \(index)" : track.trackName)
""")
}

Extract a specific track#

// Create audio block from track 0 (first track)
let audioBlockId = try engine.block.createAudioFromVideo(videoFillId, trackIndex: 0)
// Export just this track's audio
var trackAudioData = Data()
for try await case let .finished(audio) in try await engine.block.exportAudio(audioBlockId, mimeType: .wav) {
trackAudioData = audio
}

Extract all tracks#

// Create audio blocks for all tracks
let audioBlockIds = try engine.block.createAudiosFromVideo(videoFillId)
// Export each track, in order, with one stream
var trackIndex = 0
for try await case let .finished(trackData) in try await engine.block.exportAudio(audioBlockIds, mimeType: .wav) {
print("Track \(trackIndex): \(trackData.count) bytes")
trackIndex += 1
}

Complete Workflow: Audio to Captions#

A common workflow is to export audio, send it to a transcription service, and use the returned captions in your scene.

Step 1: Export Audio#

guard let page = try engine.scene.getCurrentPage() else { return }
var audioData = Data()
for try await case let .finished(audio) in try await engine.block.exportAudio(page, mimeType: .wav) {
audioData = audio
}

Step 2: Send to Transcription Service#

Send the audio to a service that returns SubRip (SRT) format captions:

Provide the endpoint and authorization header through your app’s configuration. Point the endpoint at an app-owned backend or proxy, and keep third-party service credentials out of the client.

func transcribeAudio(
_ audioData: Data,
endpoint: URL,
authorizationHeader: String
) async throws -> String {
let boundary = UUID().uuidString
var body = Data()
// Add audio file
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"audio\"; filename=\"audio.wav\"\r\n")
body.append("Content-Type: audio/wav\r\n\r\n")
body.append(audioData)
body.append("\r\n")
// Add format parameter
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"format\"\r\n\r\n")
body.append("srt")
body.append("\r\n--\(boundary)--\r\n")
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue(authorizationHeader, forHTTPHeaderField: "Authorization")
request.httpBody = body
let (data, _) = try await URLSession.shared.data(for: request)
return String(data: data, encoding: .utf8) ?? ""
}
extension Data {
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
let srtContent = try await transcribeAudio(
audioData,
endpoint: transcriptionEndpoint,
authorizationHeader: transcriptionAuthorizationHeader
)

Step 3: Import Captions from SRT#

Use the built-in API to create caption blocks from the SRT response:

import Foundation
// Save SRT to temporary file
let tempDir = FileManager.default.temporaryDirectory
let tempFile = tempDir.appendingPathComponent("captions.srt")
try srtContent.write(to: tempFile, atomically: true, encoding: .utf8)
// Import captions from file URL
let captions = try await engine.block.createCaptionsFromURI(tempFile)
// Clean up temporary file
try FileManager.default.removeItem(at: tempFile)
// Add captions to page
let captionTrack = try engine.block.create(.captionTrack)
for caption in captions {
try engine.block.appendChild(to: captionTrack, child: caption)
}
try engine.block.appendChild(to: page, child: captionTrack)
// Center the first caption as a reference point
try engine.block.alignHorizontally([captions[0]], alignment: .center)
try engine.block.alignVertically([captions[0]], alignment: .center)

Other Processing Services#

Audio export also supports these workflows:

  • Audio enhancement - Noise removal, normalization
  • Music analysis - Tempo, key, beat detection
  • Language detection - Identify spoken language
  • Speaker diarization - Identify who spoke when

Next Steps#

Now that you understand audio export, explore related audio and video features in the Create Video guides.