Play musical notes in Swift Playground
Working MIDI example in a Swift Playground
import PlaygroundSupport
import AudioToolbox
var sequence : MusicSequence? = nil
var musicSequence = NewMusicSequence(&sequence)
var track : MusicTrack? = nil
var musicTrack = MusicSequenceNewTrack(sequence!, &track)
// Adding notes
var 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, ¬e)
time += 1
}
// Creating a player
var musicPlayer : MusicPlayer? = nil
var player = NewMusicPlayer(&musicPlayer)
player = MusicPlayerSetSequence(musicPlayer!, sequence)
player = MusicPlayerStart(musicPlayer!)
PlaygroundPage.current.needsIndefiniteExecution = true
Great MIDI reference page with a nice chart
You have to enable the asynchronous mode for the Playground.
Add this at the top (Xcode 7, Swift 2):
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
and your sequence will play.
The same for Xcode 8 (Swift 3):
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true