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

时间:2016-06-10 19:48:25

标签: ios swift avaudioplayer midi

我有代码在字符串中取一系列字母并将其解释为注释。然后代码将播放笔记。问题是他们都在同一时间玩。我如何将它们作为四分音符播放,主要是为了播放音符,等待它结束,然后播放下一个音符?

@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)
    */

}

1 个答案:

答案 0 :(得分:1)

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

//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)}
  }
}

这样做是在升级延迟后播放每个音符,然后在音符长度后停止播放,这被认为是延迟常数。