【问题标题】:Unable to play a very simple tone无法演奏非常简单的音调
【发布时间】: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


【解决方案1】:

确保您的设备未处于静音模式。

我刚刚创建了一个项目,你可以自己下载测试:https://github.com/mugx/TestSound

【讨论】:

  • 它似乎在模拟器上运行良好,但在实际硬件上不是。知道为什么吗?它可能适用于您的硬件,但由于某种原因不适用于我的硬件?
  • @IHaveAQuestion 我也在物理设备上测试过,请查看答案
  • 为了以防万一,你错过了:'override func viewDidAppear(_ animated: Bool)' 的 super,那么你甚至可以投票给我的答案 :)
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2022-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
相关资源
最近更新 更多