Has anyone had any success writing native XCode/Swift code to implement ReplayGain, or similar function, or know of where I can find some example code/tutorial that does this?
I am trying to convert my python code to XCode for a native macOS application. I am using the pydub library in python and am applying a gain adjustment through the apply_gain method to normalize my audio files to a specified dBFS, but I have searched high and low for example code of how to do this in XCode and I'm coming up nearly empty handed. I'm working with Catalina 10.15.4 and XCode 11.5.
I found the below code here and I have modified it to remove the equalizer bands and add in the globalGain option. However, I now need to figure out how to analyze the file to determine the peak db/peak gain and adjust the globalGain accordingly to ensure each mp3 is nearly the same in volume without having to fiddle with the volume all the time.
import AVFoundation
var audioEngine: AVAudioEngine = AVAudioEngine()
var equalizer: AVAudioUnitEQ!
var audioPlayerNode: AVAudioPlayerNode = AVAudioPlayerNode()
var audioFile: AVAudioFile!
// in viewDidLoad():
equalizer = AVAudioUnitEQ(numberOfBands: 0)
audioEngine.attach(audioPlayerNode)
audioEngine.attach(equalizer)
let bands = equalizer.bands
//let globalGain = equalizer.globalGain
let freqs = [60, 230, 910, 4000, 14000]
audioEngine.connect(audioPlayerNode, to: equalizer, format: nil)
audioEngine.connect(equalizer, to: audioEngine.outputNode, format: nil)
equalizer.globalGain = 12
var filePath = "some_music_file.mp3"
do {
let filePathURL = NSURL.fileURL(withPath: filePath)
audioFile = try AVAudioFile(forReading: filePathURL)
audioEngine.prepare()
try audioEngine.start()
audioPlayerNode.scheduleFile(audioFile, at: nil, completionHandler: nil)
audioPlayerNode.play()
} catch {
print ("An error occured.")
}