import SwiftUI
import PlaygroundSupport
import AVFoundation
PlaygroundPage.current.wantsFullScreenLiveView = true
// variable declarations
var playing:Bool = true
var t2: Double = 1
var t1: Double = 1
var BPM:Double = 100
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
// end of variable declarations
struct DrumMachine: View{
@State var SnarePlayer: AVAudioPlayer?
var body: some View{
Button(action: {
loop1()// start buttonloop1()
}) {
Image(systemName: "play.circle")
.foregroundColor(.green)
}
.frame(width: 0.2*screenHeight, height: 0.2*screenHeight)
.scaleEffect(5)
.background(Color.clear)
//finish of play button
Button(action: {// stop button
playing = false
}) {
Image(systemName: "stop.circle")
.foregroundColor(.red)
.frame(width: 0.2*screenHeight, height: 0.2*screenHeight)
.scaleEffect(5)
.background(Color.clear)
.disabled(false)
}
.onAppear(){Snare(vol: 0)}
}//end of some view
func Snare(vol: Float){
if let SnareURL = Bundle.main.url(forResource: "Snare Drum", withExtension: "mp3") {
do {
try self.SnarePlayer = AVAudioPlayer(contentsOf: SnareURL) /// make the audio player
SnarePlayer?.volume = vol
self.SnarePlayer?.play() /// start playing
} catch {
print("Couldn't play audio. Error: \(error)")
}
}
}//end of snare function
func loop1() {
while playing == true{
for a in 1...4{
t1 = CFAbsoluteTimeGetCurrent()
Snare(vol: 2)
t2 = CFAbsoluteTimeGetCurrent()
while t2 - t1 < (1) {
t2 = CFAbsoluteTimeGetCurrent()
}
}
}
}
}//end of struct
PlaygroundPage.current.setLiveView(DrumMachine())
PlaygroundPage.current.wantsFullScreenLiveView = true