本文將教你如何列舉 MIDI(樂器數位介面)裝置,以及如何從 WinUI 應用程式發送和接收 MIDI 訊息。 Windows 支援 USB 上的 MIDI(符合類別相容且大多數專有驅動程式)、藍牙 LE 上的 MIDI,以及透過免費取得的第三方產品,支援乙太網路上的 MIDI 和路由 MIDI。
建立一個裝置監控輔助類別
Windows。Devices.Enumeration命名空間提供 DeviceWatcher,能通知應用程式是否新增或移除裝置,或裝置資訊更新。 由於支援 MIDI 的應用程式通常同時關注輸入與輸出裝置,此範例建立了一個輔助類別,實作 DeviceWatcher 模式,使同一程式碼能同時用於 MIDI 輸入與輸出裝置,無需重複。
新增一個類別到你的專案中,作為你的裝置監控器。 在此範例中,該類別命名為 MidiDeviceWatcher。 本節其餘程式碼用於實作 helper 類別。
為類別加入一些成員變數:
- 一個DeviceWatcher物件,會監控裝置變更。
- 一個裝置選擇字串,將包含一個實例的 MIDI in 埠選擇字串,以及另一個實例的 MIDI 輸出埠選擇字串。
- 一個清單 框 控制項,會用來填入可用裝置的名稱。
- 一個 DispatcherQueue ,需要從非 UI 執行緒更新 UI 的執行緒。
DeviceWatcher deviceWatcher;
string deviceSelectorString;
ListBox deviceListBox;
DispatcherQueue dispatcherQueue;
新增一個 DeviceInformationCollection 屬性,用於從輔助類別外存取目前的裝置清單。
public DeviceInformationCollection? DeviceInformationCollection { get; set; }
在類別建構子中,呼叫者會傳遞 MIDI 裝置選擇器字串、用於列出裝置的 ListBox 以及更新使用者介面所需的 DispatcherQueue 。
呼叫 DeviceInformation.CreateWatcher 建立新的 DeviceWatcher 類別實例,並傳遞 MIDI 裝置選擇字串。
為觀察者的事件處理程序註冊處理器。
public MidiDeviceWatcher(string midiDeviceSelectorString, ListBox midiDeviceListBox, DispatcherQueue dispatcher)
{
deviceListBox = midiDeviceListBox;
dispatcherQueue = dispatcher;
deviceSelectorString = midiDeviceSelectorString;
deviceWatcher = DeviceInformation.CreateWatcher(deviceSelectorString);
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Removed += DeviceWatcher_Removed;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
}
DeviceWatcher 有以下事件:
在每個事件的事件處理程序中,會呼叫一個輔助方法 UpdateDevices 來更新 ListBox 中目前的裝置清單。 由於 UpdateDevices 會更新 UI 元素,而這些事件處理程式不會在 UI 執行緒中被呼叫,因此每個呼叫都必須繞行至 DispatcherQueue.TryEnqueue。
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
dispatcherQueue.TryEnqueue(() =>
{
UpdateDevices();
});
}
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
dispatcherQueue.TryEnqueue(() =>
{
UpdateDevices();
});
}
private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
dispatcherQueue.TryEnqueue(() =>
{
UpdateDevices();
});
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
dispatcherQueue.TryEnqueue(() =>
{
UpdateDevices();
});
}
UpdateDevices 助手方法呼叫 DeviceInformation.FindAllAsync,並依本文前述所述,更新回傳裝置名稱於清單框。
private async void UpdateDevices()
{
// Get a list of all MIDI devices
this.DeviceInformationCollection = await DeviceInformation.FindAllAsync(deviceSelectorString);
deviceListBox.Items.Clear();
if (!this.DeviceInformationCollection.Any())
{
deviceListBox.Items.Add("No MIDI devices found!");
}
foreach (var deviceInformation in this.DeviceInformationCollection)
{
deviceListBox.Items.Add(deviceInformation.Name);
}
}
新增方法啟動監視器,使用 DeviceWatcher 物件的 Start 方法,以及停止監視器,使用 Stop 方法。
public void StartWatcher()
{
deviceWatcher.Start();
}
public void StopWatcher()
{
deviceWatcher.Stop();
}
提供一個解構函式來取消註冊監視者事件處理程序,並將裝置監視器設為空。
~MidiDeviceWatcher()
{
deviceWatcher.Added -= DeviceWatcher_Added;
deviceWatcher.Removed -= DeviceWatcher_Removed;
deviceWatcher.Updated -= DeviceWatcher_Updated;
deviceWatcher.EnumerationCompleted -= DeviceWatcher_EnumerationCompleted;
}
建立 MIDI 埠來傳送和接收訊息
在你視窗的程式碼中,宣告成員變數來存放兩個 MidiDeviceWatcher 助手類別的實例,一個用於輸入裝置,一個用於輸出裝置。
MidiDeviceWatcher? inputDeviceWatcher;
MidiDeviceWatcher? outputDeviceWatcher;
同時也宣告 MIDI 輸入與輸出埠物件的成員變數。
MidiInPort? midiInPort;
IMidiOutPort? midiOutPort;
建立監看程式輔助類別的新實例,並傳入裝置選擇器字串、要填入資料的 ListBox,以及 DispatcherQueue 物件。 接著,呼叫啟動每個物件的 DeviceWatcher 的方法。
每個 DeviceWatcher 啟動後不久,會完成列舉目前連接到系統的裝置,並觸發 EnumerationCompleted 事件,使每個 清單框 更新為目前的 MIDI 裝置。
inputDeviceWatcher =
new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), midiInPortListBox, DispatcherQueue);
inputDeviceWatcher.StartWatcher();
outputDeviceWatcher =
new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), midiOutPortListBox, DispatcherQueue);
outputDeviceWatcher.StartWatcher();
當使用者在 MIDI 輸入的 ListBox 中選取項目時,會觸發 SelectionChanged 事件。 在此事件的處理程序中,存取輔助類別的 DeviceInformationCollection 屬性以取得目前的裝置清單。 如果清單中有條目,請選擇 DeviceInformation 物件,其索引對應於 ListBox 控制項的 SelectedIndex。
透過呼叫
註冊一個處理程序,負責 MessageReceived 事件,當指定裝置收到 MIDI 訊息時會觸發該事件。
private async void midiInPortListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var deviceInformationCollection = inputDeviceWatcher?.DeviceInformationCollection;
if (deviceInformationCollection == null)
{
return;
}
DeviceInformation devInfo = deviceInformationCollection[midiInPortListBox.SelectedIndex];
if (devInfo == null)
{
return;
}
midiInPort = await MidiInPort.FromIdAsync(devInfo.Id);
if (midiInPort == null)
{
System.Diagnostics.Debug.WriteLine("Unable to create MidiInPort from input device");
return;
}
midiInPort.MessageReceived += MidiInPort_MessageReceived;
}
當呼叫 MessageReceived 處理器時,訊息會包含在 MidiMessageReceivedEventArgs 的 Message 屬性中。 訊息物件的 Type 是來自 MidiMessageType 枚舉中的值,表示所接收的訊息類型。 訊息的資料取決於訊息的類型。 此範例會檢查該訊息是否為 Note On 訊息,若是,則輸出該訊息的 MIDI 通道、音符與力度。
private void MidiInPort_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
{
IMidiMessage receivedMidiMessage = args.Message;
System.Diagnostics.Debug.WriteLine(receivedMidiMessage.Timestamp.ToString());
if (receivedMidiMessage.Type == MidiMessageType.NoteOn)
{
System.Diagnostics.Debug.WriteLine(((MidiNoteOnMessage)receivedMidiMessage).Channel);
System.Diagnostics.Debug.WriteLine(((MidiNoteOnMessage)receivedMidiMessage).Note);
System.Diagnostics.Debug.WriteLine(((MidiNoteOnMessage)receivedMidiMessage).Velocity);
}
}
用於輸出裝置 ListBox 的 SelectionChanged 處理常式,其運作方式與輸入裝置的處理常式相同,只是未註冊任何事件處理常式。
private async void midiOutPortListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var deviceInformationCollection = outputDeviceWatcher?.DeviceInformationCollection;
if (deviceInformationCollection == null)
{
return;
}
DeviceInformation devInfo = deviceInformationCollection[midiOutPortListBox.SelectedIndex];
if (devInfo == null)
{
return;
}
midiOutPort = await MidiOutPort.FromIdAsync(devInfo.Id);
if (midiOutPort == null)
{
System.Diagnostics.Debug.WriteLine("Unable to create MidiOutPort from output device");
return;
}
}
建立輸出裝置後,您可以建立一個新的 IMidiMessage 物件,來傳送您要傳送的訊息類型。 在此範例中,訊息為 NoteOnMessage。 呼叫 IMidiOutPort物件的 SendMessage 方法來傳送訊息。
byte channel = 0;
byte note = 60;
byte velocity = 127;
IMidiMessage midiMessageToSend = new MidiNoteOnMessage(channel, note, velocity);
midiOutPort.SendMessage(midiMessageToSend);
當你的應用程式即將關閉時,務必清理應用程式資源。 取消註冊你的事件處理器,並將 MIDI 輸入埠和輸出埠物件設為 null。 停止裝置監視器並將其設為 null。
inputDeviceWatcher?.StopWatcher();
inputDeviceWatcher = null;
outputDeviceWatcher?.StopWatcher();
outputDeviceWatcher = null;
if (midiInPort != null)
{
midiInPort.MessageReceived -= MidiInPort_MessageReceived;
midiInPort.Dispose();
midiInPort = null;
}
if (midiOutPort != null)
{
midiOutPort.Dispose();
midiOutPort = null;
}
使用內建的 Windows General MIDI 合成器
當你用上述技術列舉輸出 MIDI 裝置時,應用程式會發現一個名為「Microsoft GS Wavetable Synth」的 MIDI 裝置。 這是內建的通用 MIDI 合成器,你可以從應用程式中播放。
通用 MIDI 的 UWP 擴充 SDK(「Microsoft 通用 MIDI DLS for Universal Windows 應用程式」)在 WinUI 3 專案中無法取得。 舊版的 「新增參考 > 擴充功能 」對話框是專屬於 UWP。 然而,在大多數桌面環境下,GS Wavetable Synth 無需擴充套件 SDK 也能運作,因為桌面應用程式可以直接存取系統的 gm.dls 音色庫。 如果你發現 MIDI 輸出沒有聲音,請確認是否選擇了 MIDI 輸出裝置,且音訊輸出設定正確。