'midiplay.bas
'Bare bones MIDI player.
'A timer will watch for the end of the MIDI
'and close the midi and the window.
'from Mastering LB3 eBook
'http://alycesrestaurant.com/master.htm

nomainwin
WindowWidth=190:WindowHeight=70
button #1.b, "Open File",[open],UL,10,10,80,26
button #1.exit, "Exit",[quit],UL,100,10,80,26
open "MIDI Player" for window_nf as #1
print #1, "trapclose [quit]"

[loop]
wait


[open]
    filedialog "select MIDI","*.mid",m$ 
    if m$="" then [loop]
    m$=GetShortPathName$(m$)
    r$=mciSendString$("open "+m$+" type sequencer alias music")
    r$=mciSendString$("status music length")
    musiclength=val(r$)

    timer 100, [closeSong]

    musicOpen=1
    r$=mciSendString$("play music")
    goto [loop]


[closeSong]  'See which part of midi is currently
             'playing and if it is at the end
             'then close midi.
    r$=mciSendString$("status music position")
    if val(r$)<musiclength then [loop]
    r$=mciSendString$("close music")
    timer 0
    musicOpen=0
[quit]
    if musicOpen=1 then r$=mciSendString$("close music")
    close #1:end

Function mciSendString$(s$)
    'Buffer will contain a return string from
    'the function, if there is one.
    buffer$=space$(1024)+chr$(0)
    calldll #winmm,"mciSendStringA",s$ as ptr,buffer$ as ptr,_
        1028 as long, 0 as long, r as long

    'truncate returned string at null character
    buffer$=left$(buffer$, instr(buffer$, chr$(0)) - 1)
        if r>0 then
            mciSendString$="error"
        else
            mciSendString$=buffer$

        end if
    End Function

Function GetShortPathName$(lPath$)
    lPath$=lPath$+chr$(0)
    sPath$=space$(256)
    lenPath=len(sPath$)
    calldll #kernel32, "GetShortPathNameA",lPath$ as ptr,_
    sPath$ as ptr,lenPath as long,r as long
    GetShortPathName$=left$(sPath$,r)
    end function
