简体   繁体   English

如何在Swift中使用AVAudioEngine和AVAudioPlayerNode播放音频?

[英]How to Play Audio Using AVAudioEngine and AVAudioPlayerNode in Swift?

I'm trying to play audio using AVAudioEngine and AVAudioPlayerNode. 我正在尝试使用AVAudioEngine和AVAudioPlayerNode播放音频。 However, in "engine.connect...", I get this: 但是,在“ engine.connect ...”中,我得到了:

"PlaySound[21867:535102] [AudioHAL_Client] AudioHardware.cpp:666:AudioObjectGetPropertyData: AudioObjectGetPropertyData: no object with given ID 0" “ PlaySound [21867:535102] [AudioHAL_Client] AudioHardware.cpp:666:AudioObjectGetPropertyData:AudioObjectGetPropertyData:没有具有给定ID 0的对象

The code after "engine.connect..." seems to run because it prints "buffer?.format", but there's no sound. “ engine.connect ...”之后的代码似乎在运行,因为它显示“ buffer?.format”,但没有声音。

Could someone let me know what I'm missing? 有人可以让我知道我在想什么吗? Here's my testing code. 这是我的测试代码。

let audioNode = AVAudioPlayerNode()
let path = Bundle.main.path(forResource: "Sounds/Test.mp3", ofType: nil)
let url = URL(fileURLWithPath: path!)
let file = try! AVAudioFile(forReading: url)
let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length))
try! file.read(into:buffer!)
let engine = AVAudioEngine()
engine.attach(audioNode)
engine.connect(audioNode, to: engine.mainMixerNode, format: buffer?.format)
// PlaySound[21867:535102] [AudioHAL_Client] AudioHardware.cpp:666:AudioObjectGetPropertyData:  AudioObjectGetPropertyData: no object with given ID 0
engine.prepare()
try! engine.start()
audioNode.play()
audioNode.scheduleBuffer(buffer!, at: nil, options: .loops, completionHandler: nil)
debugPrint(buffer?.format)
// Optional(<AVAudioFormat 0x60000212d1d0:  1 ch,  44100 Hz, Float32>)

In engine.connect(), I also tried engine.outputNode.outputFormat(forBus: 0) instead of buffer?.format. 在engine.connect()中,我还尝试了engine.outputNode.outputFormat(forBus:0)而不是buffer?.format。 I got no luck. 我没有运气。

It works if I put engine outside like this: 如果我将引擎放在这样的外面,它会起作用:

class ViewController: NSViewController {
    let engine = AVAudioEngine()
    override func viewDidLoad() {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM