Unable to playback a Midi File

Viewed 31

I am trying to create and playback a sequence of MIDI, notes. However my player does not get created properly:

 func filePathReturn() -> NSURL{
    let fileMang = FileManager.default
    var filePath = NSHomeDirectory()
    do {
        let appSupportDir = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        filePath = appSupportDir.appendingPathComponent("data.mid").path
    }
    catch{}
    print(filePath)
    if fileMang.fileExists(atPath: filePath) {
        do {
            try fileMang.removeItem(atPath: filePath)
        }
        catch {}
    }

    return NSURL(fileURLWithPath: filePath)
}




func playMusic(){


    NewMusicSequence(&sequence)
    MusicSequenceNewTrack(sequence!, &track)
    let url = filePathReturn()


    let track1 = sequencer.newTrack()
    for notee in TestOne().notes{

        var number = freqsScale[notee.frequency] ?? 0
       // print(number)
        //print(notee.distance)
        number += 11
        let d1 = Duration(seconds: Double(notee.distance))
        let d2 = Duration(seconds: Double(time))
        track1?.add( midiNoteData: MIDINoteData(noteNumber: UInt8(number), velocity: 64, channel: 0, duration: d1 , position: d2 ))
        time += Double(notee.distance)

    }
    sequencer.setLength(Duration(seconds: time))
    self.soundbank = Bundle.main.url(forResource: "gs_instruments", withExtension: "gls") as NSURL?
    
    // a standard MIDI file.
    var contents:NSURL = url
    
    
    do{
        try self.mp = AVMIDIPlayer(contentsOf: contents as URL, soundBankURL: soundbank as URL?)
    }
    catch{
        print("player not created")
    }
    if self.mp == nil {
        print("nil midi player")
    }
    self.mp.prepareToPlay()
    
    self.mp.play(nil)
    
   
    var completion:AVMIDIPlayerCompletionHandler = {print("done")}
    mp.play(completion)
    url.stopAccessingSecurityScopedResource()


}

When I try to run this code, I get the following error, when I try to create the MIDI player:

TFileBSD.cpp:327 about to throw 100002: Open::fopen failed

What could be causing this and how do I fix it?

0 Answers
Related