sejal thesiya
sejal thesiya

Reputation: 64

How to play sound note (.mid file) on iOS?

I want to make piano player in which I want to play predefined notes which are some .mid files. Here is my code which is not working.

let soundPath: String? = Bundle.main.path(forResource: "0_100", ofType: "mid")
    let midiFile:URL = URL(fileURLWithPath: soundPath ?? "")
    var midiPlayer: AVMIDIPlayer?

    do {
        try midiPlayer = AVMIDIPlayer(contentsOf: midiFile, soundBankURL: nil)
        midiPlayer?.prepareToPlay()
        midiPlayer?.play {
            print("finished playing")
        }
    } catch {
        print("could not create MIDI player")
    }

Upvotes: 2

Views: 1531

Answers (1)

Cœur
Cœur

Reputation: 38667

soundBankURL is missing in the following:

try midiPlayer = AVMIDIPlayer(contentsOf: midiFile, soundBankURL: nil)

It's required according to the doc: https://developer.apple.com/documentation/avfoundation/avmidiplayer/1389225-init

Important
For macOS the bankURL can be set to nil to use the default sound bank. However, iOS must always refer to a valid bank file.

A soundBank can be a .sf2 file for instance.

Upvotes: 4

Related Questions