无法播放非常简单的音调

时间:2017-12-08 03:02:48

标签: ios swift audio avfoundation

我关注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)上运行应用程序时,它不起作用,但它可以在模拟器上运行。为什么这没有发出任何声音,怎么能我修理它?

提前致谢!

1 个答案:

答案 0 :(得分:1)

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

我刚创建了一个项目供您自行下载测试:https://github.com/mugx/TestSound