我正在开发Windows应用商店应用。我需要实现一个节拍器。这个节拍器应该有bpm设置。用户应该能够增加/减少它。
到目前为止,这是我的代码:
namespace App1
{
public sealed partial class MainPage : Page
{
public class TickArgs : EventArgs
{
public DateTime Time { get; set; }
}
public class Metronome
{
public event TickHandler Tick = (m, e) => { };
public delegate void TickHandler(Metronome m, TickArgs e);
public void Start()
{
while (true)
{
System.Threading.Tasks.Task.Delay(3000);
Tick(this, new TickArgs { Time = DateTime.Now });
}
}
}
public class Listener
{
public void Subscribe(Metronome m, TextBlock tb, MediaElement mmx)
{
m.Tick += (mm, e) => mmx.Play();
}
}
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m, tbcheck, mediaElement1);
m.Start();
}
}
}
如何修改此代码以进行BPM设置?
我的问候
答案 0 :(得分:1)
不使用Task.Delay
,而是使用Timer
您可以将BBM
传递给Start
方法并根据该方法设置间隔
public class Metronome
{
private DispatcherTimer _timer;
public event TickHandler Tick;
public delegate void TickHandler(Metronome m, TickArgs e);
public Metronome()
{
_timer = new DispatcherTimer();
_timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (Tick != null)
{
Tick(this, new TickArgs { Time = DateTime.Now });
}
}
public void Start(int bbm)
{
_timer.Stop();
_timer.Interval = TimeSpan.FromSeconds(60 / bbm);
_timer.Start();
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m, tbcheck, mediaElement1);
m.Start(8); // 8bbm
}