I am trying to play 4 mp3 files synchronously using AudioKit's AKPlayer, and it was pretty successful. As a part of my Swift study, though, I wanted to simplify my code using arrays (or something I haven't learned yet) since I feel there's something redundant in my code, simply copying player codes for four times. Below is the code I've written:
let file1 = try? AKAudioFile(readFileName: "mixing_1_vocal.mp3")
let file2 = try? AKAudioFile(readFileName: "mixing_2_drums.mp3")
let file3 = try? AKAudioFile(readFileName: "mixing_3_synth.mp3")
let file4 = try? AKAudioFile(readFileName: "mixing_4_bass.mp3")
let player1 = AKPlayer(audioFile: file1!)
let player2 = AKPlayer(audioFile: file2!)
let player3 = AKPlayer(audioFile: file3!)
let player4 = AKPlayer(audioFile: file4!)
let startTime = AVAudioTime.now() + 0.25
let mixer = AKMixer()
player1 >>> mixer
player2 >>> mixer
player3 >>> mixer
player4 >>> mixer
player1.isLooping = true
player1.buffering = .always
player2.isLooping = true
player2.buffering = .always
player3.isLooping = true
player3.buffering = .always
player4.isLooping = true
player4.buffering = .always
AudioKit.output = mixer
try? AudioKit.start()
player1.start(at: startTime)
player2.start(at: startTime)
player3.start(at: startTime)
player4.start(at: startTime)
This is it! There are four different tracks (individual instruments), and they are supposed to be played at the same time, looped infinitely. It will be very helpful if anybody could help me improve my code. Are there better ways to perform the same work?