Created
May 12, 2018 21:18
-
-
Save armadsen/f6b28a87e697d97e274884d16de54965 to your computer and use it in GitHub Desktop.
Extension to add a volume property to MIKMIDISynthesizer on iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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