我正在嘗試構建一個節拍器應用程序,該程序能夠在後臺運行。作爲一個起點,我決定創建一個簡單的東西,一個有定時器(節拍器本身)的類,一個負責獲取MIDI輸出設備的類以及一個播放聲音的類。我在如何在後臺執行此操作時遇到困難。另外,另一個問題是節拍器需要在點擊應用程序按鈕時執行(在主流程中)。當UWP進入後臺時保持MiDi輸出播放
節拍器類:
public class Metronome
{
private DispatcherTimer timer = new DispatcherTimer();
private MidiDeviceSelector deviceSelector = new MidiDeviceSelector();
private void TimerStart()
{
timer.Start();
timer.Tick += timer_Tick;
}
private void timer_Tick(object sender, object e)
{
AudioPlayback.Beep1();
}
public void Start(int bpm)
{
double interval = (double)60.000f/(bpm);
timer.Interval = TimeSpan.FromSeconds(interval);
TimerStart();
}
public void Stop()
{
timer.Stop();
}
}
MidiDeviceSelector:
class MidiDeviceSelector
{
public MidiDeviceSelector()
{
GetOutputMidiDevice();
}
public async void GetOutputMidiDevice()
{
IMidiOutPort currentMidiOutputDevice;
DeviceInformation devInfo;
DeviceInformationCollection devInfoCollection;
string devInfoId;
devInfoCollection = await DeviceInformation.FindAllAsync(MidiOutPort.GetDeviceSelector());
if (devInfoCollection == null)
{
//notify the user that any device was found.
System.Diagnostics.Debug.WriteLine("Any device was found.");
}
devInfo = devInfoCollection[0];
if (devInfo == null)
{
//Notify the User that the device not found
System.Diagnostics.Debug.WriteLine("Device not found.");
}
devInfoId = devInfo.Id.ToString();
currentMidiOutputDevice = await MidiOutPort.FromIdAsync(devInfoId);
if (currentMidiOutputDevice == null)
{
//Notify the User that wasn't possible to create MidiOutputPort for the device.
System.Diagnostics.Debug.WriteLine("It was not possible to create the OutPort for the device.");
}
MidiDevice.midiDevice = currentMidiOutputDevice;
}
類來盛放MidiDevice的:
class MidiDevice
{
public static IMidiOutPort midiDevice; //Bad practice i know.
}
類打 「TOC」 的聲音:
class AudioPlayback
{
static IMidiMessage beep1 = new MidiNoteOnMessage(9, 76, 90);
//static IMidiOutPort midiOutputDevice = (IMidiOutPort)MidiDeviceSelector.GetOutputMidiDevice();
public static void Beep1()
{
try
{
MidiDevice.midiDevice.SendMessage(beep1);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
}
每個類都包含在不同的文件中。正如你所看到的,這是一個非常簡單的代碼,如果你看到任何不好的編程習慣,我道歉,我沒有太多的經驗。
我在看文檔,但是,我沒有成功。如何在後臺註冊一項活動,並且與應用程序的用戶界面(一個用於停止和啓動節拍器的按鈕)進行交互。
我對不好的英語而不是我的母語表示歉意。
謝謝。你需要添加,使這個方案的工作
你需要在UI的地方創建按鈕。然後,您可以將事件處理程序添加到其Click事件中以調用_timer.Start和_timer.Stop。 Happy googling :) – hoodaticus
我已更新標題以更好地反映您嘗試解決的問題併發布了新答案。我也已經相應地更新了你的樣本,它現在按預期工作。 –
請注意'DispatcherTimer'不是超精確的,所以對於節拍器可能不是一個好的選擇。 –