導入winmm.dll中的函數mciSendStringide
[DllImport("winmm.dll")] static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);
須要注意的是,全部命令須要在同一個線程中,才能夠對同一個midi實例進行控制。該函數經過字符串向聲卡發送指令,常見的用於播放midi文件的指令有如下:函數
1.打開文件ui
mciSendString($"open {file} type {device} alias {alias}", null, 0, new IntPtr());
{file}: 文件名,須要打開的midi文件路徑;spa
{device}: 設備名稱,通常填寫」sequencer」,不過筆者發現填寫」mpegvideo」會顯著提升加載midi的速度;線程
{alias}: 別名,用於後續對該midi的控制。code
2.播放文件orm
mciSendString($"play {alias} [repeat]", null, 0, new IntPtr());
{alias}: 前文提到的別名;blog
[repeat]: 可選指令,能夠循環播放。ci
3.獲取文件時長字符串
mciSendString("set {alias} time format milliseconds", null, 0, new IntPtr()); mciSendString("status {alias} length", result, 100, new IntPtr());
首先將時間格式設置爲毫秒,而後將時間讀取到result變量中。
4.中止播放
mciSendString($"stop {alias}", null, 0, new IntPtr());
5.關閉文件
mciSendString($"close {alias}", null, 0, new IntPtr());