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

我有代码来获取string中的字母序列,并将其解释为笔记。 代码然后将播放音符。 问题是他们都在同一时间玩。 我怎么把它们当作四分音符来演奏,主要是为了演奏一个音符,等待它结束,然后演奏下一个音符?

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

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