我正在尝试构建一个能够在后台运行的节拍器应用程序。作为一个起点,我决定创造一些简单的东西,一个有定时器(节拍器本身)的类,一个负责获取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);
}
}
}
每个类都包含在不同的文件中。正如你所看到的,这是一个非常简单的代码,如果你看到任何糟糕的编程习惯,我道歉,我没有太多的经验。
我正在查看文档,但是,我没有成功。如何在后台注册活动以及与应用程序的用户界面进行交互(用于停止和启动节拍器的按钮)。
我对英语不好而不是我的母语表示道歉。
谢谢。
答案 0 :(得分:0)
要使此方案有效,您需要添加两件事:
添加“backgroundMediaPlayback”功能,如下所示:https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/background-audio
由于您使用的是MiDI API,因此您需要明确地与SystemMediaTransportControl集成,以防止在最小化时获得静音
我已经更新了您的repro示例,并在添加这两项内容后验证它是否正常工作。