0

Beginner of programming. The code below can sounds fine, but repeats the same tone 5 times. I want to change tone each time it's called. Please help me to solve this problem. (I don't have Mac but iPad only. And making programs with Swift Playgrounds.)

//Swift5.3, iPadOS14
let tones = ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"]    // 1~2seconds short aiff format sounds

func indexNum()->Int {
    let randInt = Int.random(in: 1...7)    //except "C4" on purpose.
    return randInt
}

let toneURL = Bundle.main.url(forResource: tones[indexNum()], withExtension: "aiff")!    //You may think this weird, that's because i'm writing with iPad Playgrounds. But this can sound fines.
let tone = SKAudioNode(url: toneURL)
tone.autoplayLooped = false
self.addChild(tone)

let c4URL = Bundle.main.url(forResource: tones[0], withExtension: "aiff")!    // Can replace "C4" instead of tones[0]
let c4 = SKAudioNode(url: c4URL)
c4.autoplayLooped = false
self.addChild(c4)

let randNum = SKAction.run{ [self] in
indexNum()
}
let tonePlay = SKAction.run {
    tone.run(SKAction.play())
}
let c4Play = SKAction.run {
    c4.run(SKAction.play())
}
let wait = SKAction.wait(forDuration: 1.5)
let rfp = SKAction.removeFromParent()
let seq = SKAction.sequence([randNum, wait, tonePlay, rfp, wait, c4Play, rfp])
let rep = SKAction.repeat(seq, count: 5)
self.run(rep)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • You should be able to create a function also in the playground that you call from a loop over the tomes array. _Edit_ I see now there is a reference to self in the code so you already have a function and a type. Still the advice applies, move the relevant code to a separate function and call it from a loop – Joakim Danielson Aug 27 '21 at 06:14

2 Answers2

0

This is the answer from Japanese site. (I'm Japanese) And it works!

let tones = ["C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"] 
func indexNum()->Int {
    let randInt = Int.random(in: 1...7)
    return randInt
}

func random(){
let toneURL = Bundle.main.url(forResource: tones[indexNum()], withExtension: "aiff")!
let tone = SKAudioNode(url: toneURL)
    tone.autoplayLooped = false
    self.addChild(tone)
    tone.run(SKAction.play())
}


let c4URL = Bundle.main.url(forResource: tones[0], withExtension: "aiff")!
let c4 = SKAudioNode(url: c4URL)
c4.autoplayLooped = false
self.addChild(c4)

let randNum = SKAction.run(random)
let c4Play = SKAction.run {
    c4.run(SKAction.play())
}
let wait = SKAction.wait(forDuration: 1.5)
let rfp = SKAction.removeFromParent()
let seq = SKAction.sequence([ wait, randNum, rfp, wait, c4Play, rfp])
let rep = SKAction.repeat(seq, count: 5)
self.run(rep)
  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Aug 28 '21 at 08:39
0

It's not my own solution. (I got this from Japanese site.) So I'm not sure, but making random func and running as SKAction make it work I think.