Play musical notes in Swift Playground Play musical notes in Swift Playground ios ios

Play musical notes in Swift Playground


You have to enable the asynchronous mode for the Playground.

Add this at the top (Xcode 7, Swift 2):

import XCPlaygroundXCPlaygroundPage.currentPage.needsIndefiniteExecution = true

and your sequence will play.

The same for Xcode 8 (Swift 3):

import PlaygroundSupportPlaygroundPage.current.needsIndefiniteExecution = true


Working MIDI example in a Swift Playground

import PlaygroundSupportimport AudioToolboxvar sequence : MusicSequence? = nilvar musicSequence = NewMusicSequence(&sequence)var track : MusicTrack? = nilvar musicTrack = MusicSequenceNewTrack(sequence!, &track)// Adding notesvar time = MusicTimeStamp(1.0)for index:UInt8 in 60...72 { // C4 to C5    var note = MIDINoteMessage(channel: 0,                               note: index,                               velocity: 64,                               releaseVelocity: 0,                               duration: 1.0 )    musicTrack = MusicTrackNewMIDINoteEvent(track!, time, &note)    time += 1}// Creating a playervar musicPlayer : MusicPlayer? = nilvar player = NewMusicPlayer(&musicPlayer)player = MusicPlayerSetSequence(musicPlayer!, sequence)player = MusicPlayerStart(musicPlayer!)PlaygroundPage.current.needsIndefiniteExecution = true

Great MIDI reference page with a nice chart

MIDI Notes Reference


matomo