我目前正在使用 ARKit 和 SceneKit 开发 AR 应用程序,并且在 ViewController 类中遇到了音频播放问题。我有一个 SCNNode,它代表我的 ARSCNView 中的旋转和移动框。我想使用 SCNAudioPlayer 将音频播放添加到该节点。
我已经设置了音频源并使用addAudioPlayer方法将其添加到SCNNode,但由于某种原因,音频在场景执行期间似乎没有播放。我已确保音频文件 (sample_audio.mp3) 位于正确的位置,并且 SCNAudioSource 已正确初始化和加载。
我在下面包含了代码的简化版本:
class ViewController: UIViewController {
// MARK: - Property
var scene: SCNScene!
// MARK: - execute
private func execute() {
action_example2()
}
// MARK: - UIComponents
private lazy var arSceneView: ARSCNView = {
$0.delegate = self
$0.showsStatistics = true
return $0
}(ARSCNView())
}
extension ViewController {
func action_example1() {
let scene = SCNScene()
arSceneView.scene = scene
let boxGeometry = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0.1)
var boxNode = SCNNode()
boxNode = SCNNode(geometry: boxGeometry)
boxNode.position = SCNVector3(0, 0, -5)
let material = SCNMaterial()
material.diffuse.contents = UIImage(resource: .pyramidFull)
boxNode.geometry?.firstMaterial = material
scene.rootNode.addChildNode(boxNode)
let rotateAction = SCNAction.rotateBy(x: 0, y: .pi, z: 0, duration: 2)
let moveAction = SCNAction.move(to: SCNVector3(0, 0, -10), duration: 2)
let sequenceAction = SCNAction.sequence([rotateAction, moveAction])
let repeatAction = SCNAction.repeatForever(sequenceAction)
let audioSource = SCNAudioSource(fileNamed: "sample_audio.mp3")!
audioSource.loops = true
audioSource.load()
boxNode.addAudioPlayer(SCNAudioPlayer(source: audioSource))
boxNode.runAction(repeatAction)
}
}
我已采取以下步骤来解决音频播放问题:
使用音频文件名 (sample_audio.mp3) 创建一个新的 SCNAudioSource 实例,并将 Loops 属性设置为 true。 使用 load() 方法加载音频源以确保其准备好播放。 使用 addAudioPlayer 方法将 SCNAudioPlayer 添加到 SCNNode。 我预计通过这些步骤,音频文件将随着 SCNNode 在 ARSCNView 场景中的动画而连续播放。然而,尽管做出了这些努力,音频在场景执行期间似乎并未播放。
有什么我可能会忽略的东西或者需要额外的配置才能在此 ARSCNView 场景中成功播放音频吗?
作为问题的快速解决方案,您可以考虑以下“解决方法”:
而不是像这样添加音频播放器
boxNode.addAudioPlayer(SCNAudioPlayer(source: audioSource))
尝试类似的操作 - 向节点添加一个额外的操作:
boxNode.runAction(SCNAction.playAudio(audioSource, waitForCompletion: false))
您还可以考虑使用
AVFoundation
框架并使用(作为简化示例):
do { soundSession = try AVAudioPlayer(contentsOf: url) } catch { print(error) }
然后:
soundSession.volume = defaultVolume
soundSession.numberOfLoops = numberOfLoops // -1 for endless looping, 0 for once
soundSession.currentTime = 0.0
soundSession.play()
PS:还要确保正确访问 MP3 文件:i.Ex。像这样:
SCNAudioSource(fileNamed: "art.scnassets/soundeffects/Blastwave_FX_BasketballBounce_AP1.1290.wav")!
希望能给一些指导。