无法演奏非常简单的音调
Unable to play a very simple tone
我正在关注 ,但我尝试使用 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
是一个 class 变量,因此不应从内存中释放它。
当我 运行 我的物理设备上的应用程序 (iPhone 6s iOS 11),它不工作,但它在模拟器上工作. 为什么这没有任何声音,我该如何解决?
提前致谢!
确保您的设备未处于静音模式。
我刚刚创建了一个项目,你可以自己下载测试:https://github.com/mugx/TestSound
我正在关注
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
是一个 class 变量,因此不应从内存中释放它。
当我 运行 我的物理设备上的应用程序 (iPhone 6s iOS 11),它不工作,但它在模拟器上工作. 为什么这没有任何声音,我该如何解决?
提前致谢!
确保您的设备未处于静音模式。
我刚刚创建了一个项目,你可以自己下载测试:https://github.com/mugx/TestSound