I can't figure out how to get audio from my RealityKitContentBundle to play on Vision Pro...
I have a scene in Reality Composer Pro called "WinterVivarium" which contains a 3D model of a tree, a particle emitter, a ChannelAudio entity, and an audio file (m4a) with 30 minutes of nature sounds.
The 3D model and particle emitter load up just fine on my device, but I'm getting an error when I try to load the audio...
Swift file below. When I run the app and this file gets called it throws the following error:
"Error loading winter vivarium model and/or audio: The operation couldn’t be completed. (RealityKit.__REAsset.LoadError error 2.)"
ChatGPT tells me error code 2 likely means "file not found" but I'm not sure on that one...
Please help!
import SwiftUI
import RealityKit
import RealityKitContent
struct WinterVivarium: View {
@State private var angle: Angle = .degrees(0)
var body: some View {
RealityView { content in
let audioFilePath = "/Root/back-yard-feb-7am.m4a"
let audioEntity = Entity()
do {
let entity = try await Entity(named: "WinterVivarium", in: realityKitContentBundle)
content.add(entity)
let resource = try await AudioFileResource.load(named: audioFilePath, from: "WinterVivarium.usda", in: RealityKitContent.RealityKitContentBundle)
let audioController = audioEntity.playAudio(resource)
} catch {
print("Error loading winter vivarium model and/or audio: \(error.localizedDescription)")
}
}
}
#Preview {
WinterVivarium()
}
After 4 long months I finally got my audio playing!!!
I used the method Dilmer Valecillos describes in his YouTube video here: https://www.youtube.com/watch?v=eMA1Vd1nc9M
Skip to @44:40 to let him walk you through the solution.
Here is my working file for reference:
import SwiftUI
import RealityKit
import RealityKitContent
struct WinterVivarium: View {
@State private var audioController: AudioPlaybackController?
var body: some View {
RealityView { content in
guard let entity = try? await Entity(named: "WinterVivarium", in: realityKitContentBundle) else {
fatalError("Unable to load WinterVivarium")
}
let ambientAudioEntity = entity.findEntity(named: "ChannelAudio")
guard let resource = try? await AudioFileResource(named: "/Root/back_yard_feb_7am_m4a", from: "WinterVivarium.usda", in: realityKitContentBundle) else {
fatalError("Unable to find audio file back_yard_feb_7am_m4a")
}
audioController = ambientAudioEntity?.prepareAudio(resource)
audioController?.play()
content.add(entity)
}
.onDisappear(perform: {
audioController?.stop()
})
}
}
#Preview {
WinterVivarium()
}