I'm new to swift and am trying to build a step sequencer as a project.
You tap on a pattern and the code runs through each step at a specified bpm and plays the selected sound if the step is on. Fine so far. But I can't figure out how to have two different sounds play simultaneously, which can happen when there's more than one instrument.
I looked at async and concurrency a few times but I can't wrap my head around it.
If a sound and the same sound with an inverted phase are played at the same time, the waves cancel each other out, so nothing should be heard. This doesn't happen.
Test that I made:
import SwiftUI
import AVFoundation
import Foundation
struct ContentView: View {
@State var playerA: AVAudioPlayer!
@State var playerB: AVAudioPlayer!
func playSound() {
let urlA = Bundle.main.url(forResource: "sound", withExtension: "wav")
let urlB = Bundle.main.url(forResource: "sound_inverted", withExtension: "wav")
playerA = try! AVAudioPlayer(contentsOf: urlA!)
playerB = try! AVAudioPlayer(contentsOf: urlB!)
playerA.play()
playerB.play()
}
var body: some View {
HStack{
Button(action:{
playSound()
}, label: {
Text( "TRY")
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
What happens is that when the button is pressed the two sounds are played and are audible.
I tried async but I don't understand where to put what or how to structure this whole thing because it always throws up some errors.