【发布时间】:2017-12-08 03:02:48
【问题描述】:
我正在关注this question,但我尝试使用 AVAudioPCMBuffer 播放的音调无法播放。代码很简单:
class Player: NSObject {
var engine = AVAudioEngine()
var player = AVAudioPlayerNode()
var mixer: AVAudioMixerNode!
var buffer: AVAudioPCMBuffer!
override init() {
mixer = engine.mainMixerNode
buffer = AVAudioPCMBuffer(pcmFormat: player.outputFormat(forBus: 0), frameCapacity: 100)
buffer.frameLength = 100
let sr = mixer.outputFormat(forBus: 0).sampleRate
let nChannels = mixer.outputFormat(forBus: 0).channelCount
var i = 0
while i < Int(buffer.frameLength) {
let val = sin(441 * Double(i) * Double.pi / sr)
buffer.floatChannelData?.pointee[i] = Float(val * 0.5)
i += Int(nChannels)
}
engine.attach(player)
engine.connect(player, to: mixer, format: player.outputFormat(forBus: 0))
engine.prepare()
}
func play() {
do {
try engine.start()
} catch {
print(error)
}
player.scheduleBuffer(buffer, at: nil, options: .loops) {
print("Played!")
}
player.play()
}
}
但由于某种原因,iPhone 没有发出任何声音。在我的 ViewController 中,我有这个:
class ViewController: UIViewController {
var player = Player()
override func viewDidAppear(_ animated: Bool) {
player.play()
}
}
如您所见,player 是一个类变量,因此不应从内存中释放它。
当我在我的物理设备(iPhone 6s iOS 11)上运行该应用程序时,它无法运行,但它在模拟器上运行。为什么它没有发出任何声音,以及如何我修复它?
提前致谢!
【问题讨论】:
-
对我来说,你的代码运行良好,我的意思是我能听到声音
-
@AndreaMugnaini,哪个设备和 iOS?我在运行 iOS 11 全音量的硬件上
标签: ios swift audio avfoundation