AVAudioUnitSampler generates sinusoids after changing the route of headphones, iOS 11 iPhone

When using AVAudioUnitSampler, I had a strange problem on the iPhone (iOS 11).

Say I have an AVAudioUnitSampler initialized with a piano sound. Thus, every time I connect or disconnect the headphones, I hear a piano sound plus a sinusoidal tone added to it, which gets louder the more I plug / unplug the headphones.

So, it seems to me that every time the headphones are connected / not connected, a new audio node can be connected to the audio output (and, since it is not initialized, it only generates sinusoidal tones).

The next class already shows the problem. Please note that I use AudioKit for processing signals and MIDI sampler run (although, to this end everything is working properly, that is startNote(), and stopNote()properly called):

class MidiController: NSObject, AKMIDIListener {

    var midi = AKMIDI()
    var engine = AVAudioEngine()
    var samplerUnit = AVAudioUnitSampler()

    override public init() {
        super.init()

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleRouteChange),
            name: .AVAudioSessionRouteChange,
            object: nil)

        midi.openInput()
        midi.addListener(self)
        engine.attach(samplerUnit)
        engine.connect(samplerUnit, to: engine.outputNode)
        startEngine()
    }

    func startEngine() {
        if (!engine.isRunning) {
            do {
                try self.engine.start()
            } catch  {
                fatalError("couldn't start engine.")
            }
        }
    }

    @objc func handleRouteChange(notification: NSNotification) {
        let deadlineTime = DispatchTime.now() + .milliseconds(100)
        DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
            self.startEngine()
        }
    }

    func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity:MIDIVelocity, channel: MIDIChannel) {
        if velocity > 0 {
            samplerUnit.startNote(noteNumber: noteNumber, velocity: 127, channel: 0)
        } else {
            samplerUnit.stopNote(noteNumber: noteNumber, channel: 0)
        }
    }

    func receivedMIDINoteOff(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) {
        samplerUnit.stopNote(noteNumber: noteNumber, channel: 0)
    }
}

I forked AudioKit and replaced the HelloWorld example with a minimal project with which I can reproduce this problem.

In addition, I could not reproduce this problem on the iPad under iOS 9.3 and 11, so this could be an iPhone problem.

Any help or suggestion on how to continue debugging would be very welcome, I am very puzzled by this, and I am not an expert in iOS audio development.

Thank!

+4
source share
1 answer

, handleRouteChange, , . , .

+2

Source: https://habr.com/ru/post/1688883/


All Articles