Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extension to add a volume property to MIKMIDISynthesizer on iOS
//
// MIKMIDISynthesizer+Volume.swift
//
// Created by Andrew Madsen on 3/22/16.
// Copyright © 2016 Mixed In Key. All rights reserved.
//
import Foundation
import CoreAudio
import MIKMIDI
extension MIKMIDISynthesizer {
private func linearGainToDB(gain: Float) -> Float { return 20.0 * log10(gain) }
private func DBToLinearGain(db: Float) -> Float { return pow(10.0, db / 20.0) }
var volume: Float {
get {
var result: Float = 0.0
let err = AudioUnitGetParameter(instrumentUnit, kAUSamplerParam_Gain, kAudioUnitScope_Global, 0, &result)
if err != noErr {
NSLog("Error getting volume of MIKMIDISynthesizer \(self): \(err)")
return 0.0
}
return min(max(DBToLinearGain(result), 0.0), 1.0)
}
set {
let valueInDB = linearGainToDB(min(max(newValue, 0.0), 1.0))
let err = AudioUnitSetParameter(instrumentUnit, kAUSamplerParam_Gain, kAudioUnitScope_Global, 0, valueInDB, 0);
if err != noErr { NSLog("Error setting volume of MIKMIDISynthesizer \(self): \(err)") }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment