我设置了一个节拍器项目。我有一个水龙头按钮,可以检查节拍的节奏并将其平均。每一点数学运算都正常,因为我用计算器检查了它。这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
namespace Metronome
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer3_Tick(object sender, EventArgs e)
{
// Convert tempo to timer1.Tick (miliseconds between each beat)
timer1.Interval = Convert.ToInt32(60000 / numericUpDown1.Value);
}
private void button1_Click(object sender, EventArgs e)
{
// Play / Pause button
if (button1.Text == "Go!") { timer1.Enabled = true; button1.Text = "Stop!"; }
else if (button1.Text == "Stop!") { timer1.Enabled = false; button1.Text = "Go!"; }
}
private void timer1_Tick(object sender, EventArgs e)
{
// The 'ding' sound for the metronome
SystemSounds.Beep.Play();
}
private void button2_Click(object sender, EventArgs e)
{
// Set the tempo to be the average of the convertion from miliseconds between 2 beats and the current tempo
if (timer2.Enabled) { numericUpDown1.Value = ((60000 / Tap) + numericUpDown1.Value) / 2; Tap = 0; }
else timer2.Enabled = true;
}
int Tap = 0;
private void timer2_Tick(object sender, EventArgs e)
{
// Get the amount of miliseconds between each beat
Tap++;
}
private void button3_Click(object sender, EventArgs e)
{
// Reset the tap timer
timer2.Enabled = false;
Tap = 0;
}
}
}
问题在于timer2_Tick,因为它应该每隔一毫秒添加1,相反,当我尝试它时,它会变成一个像20或30这样的小数字。我该如何解决这个问题?
答案 0 :(得分:2)
在选择使用哪个计时器时,我总是依赖一篇非常好的文章:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
我建议使用其中一个线程选项。具体来说,文章说明窗体形式计时器(System.Windows.Forms.Timer
):
如果您正在寻找节拍器,那么您来错了地方。
答案 1 :(得分:0)
如果您只需要检查按钮点按之间的时间,请使用StopWatch
。它为您提供高精度的计时机制。您自己无需计算毫秒数。