Last active
April 4, 2020 20:43
-
-
Save genedelisa/522edb2c656b1ce4fe42 to your computer and use it in GitHub Desktop.
Swift AVMIDIPlayer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// soundbanks are either dls or sf2. see http://www.sf2midi.com/ | |
var soundbank:NSURL! | |
var mp:AVMIDIPlayer! | |
func playMIDIFile() { | |
// Load a SoundFont or DLS file. | |
self.soundbank = NSBundle.mainBundle().URLForResource("GeneralUser GS MuseScore v1.442", withExtension: "sf2") | |
// a standard MIDI file. | |
var contents:NSURL = NSBundle.mainBundle().URLForResource("ntbldmtn", withExtension: "mid") | |
var error:NSError? | |
self.mp = AVMIDIPlayer(contentsOfURL: contents, soundBankURL: soundbank, error: &error) | |
if self.mp == nil { | |
println("nil midi player") | |
} | |
if let e = error { | |
println("Error \(e.localizedDescription)") | |
} | |
self.mp.prepareToPlay() | |
self.mp.play(nil) | |
// there is a crash when you use a completion | |
//self.mp.play({ | |
// println("midi done") | |
//}) | |
// or | |
// var completion:AVMIDIPlayerCompletionHandler = {println("done")} | |
// mp.play(completion) | |
} | |
func toggleMIDIPlayer() { | |
if mp.playing { | |
mp.stop() | |
} else { | |
self.mp.play(nil) | |
} | |
} | |
func stopMIDIPLayer() { | |
if mp.playing { | |
mp.stop() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't seem to work using Swift 3.
println
no longer works, andself
flags errors. I've tried modifying the code, and got rid of all the errors, but the midi file only plays for a micro-second. It seems some way of "holding on" to the process is needed.NB: if soundbank is Nil, then it uses the default DLSMusicDevice bank. I haven't found a way of specifying it explicitly.