Quantcast
Channel: FlexMonkey
Viewing all articles
Browse latest Browse all 257

Sound Synthesis in Swift Revisited with AudioKit

$
0
0
Back in October last year, I took a look at using some work on Core Audio by Gene De Lisa to synthesise audio. Since then, I've been reading about the amazing work done by the AudioKit team with their libraries for audio synthesis under iOS and OS X. With that in mind, I've updated my original project to use AudioKit.

The first thing I did was to follow the excellent tutorials on the AudioKit site. These cover the basics: how to import AudioKit into my project and create a bridging header. 

The next step was to rewrite my SoundGenerator class. There was a lot of boiler plate code in there before and AudioKit has simplified this by an order of magnitude. The class now has two methods. The first, setUp(), populates an array of FMSynth instances, adds them to AKOrchestra and invokes play() on each one:

    var oscillators = [FMSynth]()
    
    func setUp()
    {
        for i in0 ..< Constants.numInstruments
        {
            let fmOscillator = FMSynth()
            AKOrchestra.addInstrument(fmOscillator)
            
            oscillators.append(fmOscillator)
        }

        AKOrchestra.start()

        for fmOscillator inoscillators
        {
            fmOscillator.play()
        }

    }

When the user changes either the frequency or amplitude of one of the four channels, I update the appropriate property according through the playNoteOn() method:

    func playNoteOn(value: FrequencyAmplitudePair, channelNumber: Int)
    {
        let scaledFrequency = 0 + (value.frequency * Constants.frequencyScale)

        oscillators[channelNumber].amplitude.setValue(value.amplitude / 2.0, forKey: "value")
        
        oscillators[channelNumber].frequency.setValue(scaledFrequency, forKey: "value")

    }

My FMSynth class is pretty much lifted from the AudioKit tutorials:

class FMSynth: AKInstrument
{

    var frequency = AKInstrumentProperty(value: 0,  minimum: 0, maximum: Constants.frequencyScale)
    var amplitude = AKInstrumentProperty(value: 0, minimum: 0,   maximum: 0.5)
    
    overrideinit()
    {
        super.init()
        
        addProperty(frequency)
        addProperty(amplitude)
        
        let fmOscillator = AKFMOscillator()
        
        fmOscillator.baseFrequency = frequency
        fmOscillator.amplitude = amplitude
        
        connect(fmOscillator)
        connect(AKAudioOutput(audioSource: fmOscillator))
    }

}

The full source code for my project is available at my GitHub repository here. Thanks again to AudioKit for a great library!


Viewing all articles
Browse latest Browse all 257

Latest Images

Trending Articles



Latest Images