0

编程初学者。下面的代码听起来不错,但会重复相同的音调 5 次。我想在每次调用时改变音调。请帮我解决这个问题。(我没有 Mac,只有 iPad。用 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)
4

2 回答 2

0

这是来自日本网站的答案。(我是日本人)而且它有效!

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)
于 2021-08-28T07:00:27.610 回答
0

这不是我自己的解决方案。(我从日本网站得到这个。)所以我不确定,但我认为随机函数和运行 SKAction 让它工作。

于 2021-08-30T02:35:57.370 回答