如何使用 Swift 采样器播放一个音调然后在播放下一个音调之前暂停?

How do I use the Swift sampler to play a tone then pause before playing the next?

我有代码可以获取字符串中的一系列字母并将它们解释为注释。然后代码将播放音符。问题是他们都在同一时间玩。如何将它们分别作为四分音符演奏,本质上是演奏一个音符,等待它结束,然后演奏下一个音符?

@IBAction func playButton(sender: AnyObject) {
    fractalEngine.output = "adgadefe"
    var notes = Array(fractalEngine.output.characters)

    var counter = 0
    while counter < notes.count {

            var note = notes[counter]
            if note == "a" {
                play(58)
            }
            else if note == "b" {
                play(59)
            }
            else if note == "c" {
                play(60)
            }
            else if note == "d" {
                play(61)
            }
            else if note == "e" {
                play(62)
            }
            else if note == "f" {
                play(63)
            }
            else {
                play(64)
            }

            counter += 1
    }


    //self.sampler.startNote(60, withVelocity: 64, onChannel: 0)
}

func play(note: UInt8) {
    sampler.startNote(note, withVelocity: 64, onChannel: 0)
}

func stop(note: UInt8) {
    sampler.stopNote(note, onChannel: 0)

}

这是启动采样器的代码:

func initAudio(){

     engine = AVAudioEngine()
     self.sampler = AVAudioUnitSampler()
     engine.attachNode(self.sampler)
     engine.connect(self.sampler, to: engine.outputNode, format: nil)

     guard let soundbank = NSBundle.mainBundle().URLForResource("gs_instruments", withExtension: "dls") else {

     print("Could not initalize soundbank.")
     return
     }

     let melodicBank:UInt8 = UInt8(kAUSampler_DefaultMelodicBankMSB)
     let gmHarpsichord:UInt8 = 6
     do {
     try engine.start()
     try self.sampler.loadSoundBankInstrumentAtURL(soundbank, program: gmHarpsichord, bankMSB: melodicBank, bankLSB: 0)

     }catch {
     print("An error occurred \(error)")
     return
     }

    /*
    self.musicSequence = createMusicSequence()
    createAVMIDIPlayer(self.musicSequence)
    createAVMIDIPlayerFromMIDIFIle()
    self.musicPlayer = createMusicPlayer(musicSequence)
    */

}

看来你需要依次延迟播放。这是一种实现(避免阻塞主线程)。

//global delay helper function
func delay(delay:Double, closure:()->()) {
  dispatch_after(
    dispatch_time(
      DISPATCH_TIME_NOW,
      Int64(delay * Double(NSEC_PER_SEC))
    ),
    dispatch_get_main_queue(), closure)
}

//inside your playButton
let delayConstant = 0.05 //customize as needed
for (noteNumber, note) in notes.enumerate() {
  delay(delayConstant * noteNumber) {
    play(note)
    //handle stopping
    delay(delayConstant) {stop(note)}
  }
}

这样做是在不断增加的延迟后播放每个音符,然后在假定为延迟常数的音符长度后停止播放。