3

I was following this question, but the tone that I try to play with an AVAudioPCMBuffer does not play. The code is pretty simple:

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()
    }
}

For some reason, though, the iPhone does not make any sound. In my ViewController, I have this:

class ViewController: UIViewController {
    var player = Player()

    override func viewDidAppear(_ animated: Bool) {
        player.play()
    }

}

As you can see, player is a class variable, so it should not be deallocated from memory.

When I run the app on my physical device (iPhone 6s iOS 11), it does not work, yet it does work on the simulator. Why is this not making any sound, and how can I fix it?

Thanks in advance!

IHaveAQuestion
  • 789
  • 8
  • 26

1 Answers1

1

Make sure your device is not on silent mode.

I just created a project that you can download for testing by yourself: https://github.com/mugx/TestSound

Community
  • 1
  • 1
mugx
  • 9,869
  • 3
  • 43
  • 55
  • It seems that it works fine on the Simulator, but *not* on the actual hardware. Any idea why? Might it work on your hardware but for some reason not mine? – IHaveAQuestion Dec 08 '17 at 03:20
  • @IHaveAQuestion I also tested on a physical device, please check the answer – mugx Dec 08 '17 at 03:27
  • and just in case, you was missing: the super for 'override func viewDidAppear(_ animated: Bool)', then you can even upvote my answer :) – mugx Dec 08 '17 at 03:36