C# 使用.Net Forms C中的计时器在预先指定的时间内播放声音#
我在.Net Windows窗体中遇到问题。在这里,我需要单击一个图像并在由变量(“im.duration”)定义的特定持续时间内播放声音。我还有一个计时器,附带了tick Eventhandler。根据下面的代码,声音不停地重复播放 如何进行调整以使声音在指定的持续时间内播放C# 使用.Net Forms C中的计时器在预先指定的时间内播放声音#,c#,.net,C#,.net,我在.Net Windows窗体中遇到问题。在这里,我需要单击一个图像并在由变量(“im.duration”)定义的特定持续时间内播放声音。我还有一个计时器,附带了tick Eventhandler。根据下面的代码,声音不停地重复播放 如何进行调整以使声音在指定的持续时间内播放 private void Image_Click(object sender, EventArgs e) { foreach (Image im in panel2.Control
private void Image_Click(object sender, EventArgs e)
{
foreach (Image im in panel2.Controls.OfType<Image>())
{
if (sender == im)
{
timer1.Enabled = true;
count = 0;
timer1.Start();
string fileToPlay = Environment.CurrentDirectory + @"\ImageSound\" + im.sound.ToString() + ".wav";
SoundPlayer sp = new SoundPlayer(fileToPlay);
while (count <= im.Duration)
{
sp.Play();
}
timer1.Enabled = false;
sp.Stop();
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count++;
}
private void Image\u单击(对象发送方,事件参数e)
{
foreach(panel2.Controls.OfType()中的图像im)
{
如果(发送方==im)
{
timer1.Enabled=true;
计数=0;
timer1.Start();
字符串fileToPlay=Environment.CurrentDirectory++“\ImageSound\”+im.sound.ToString()+“.wav”;
SoundPlayer sp=新的SoundPlayer(fileToPlay);
(count假设Duration
是播放声音文件的毫秒数,则可以执行以下操作:
private async void Image_Click(object sender, EventArgs e)
{
Image im = (Image)sender;
string fileToPlay = System.IO.Path.Combine(Environment.CurrentDirectory, "ImageSound", im.sound.ToString() + ".wav");
SoundPlayer sp = new SoundPlayer(fileToPlay);
sp.Play();
await Task.Delay(im.Duration);
sp.Stop();
}
如果Duration
是秒数,则将im.Duration
更改为TimeSpan.FromSeconds(im.Duration)
在我的测试中,这成功地以我指定的更短的持续时间切断了一个8秒的.wav文件
请注意,对于
循环,我们根本不需要。我们只需将发送方
强制转换为类图像
顺便说一句,Image
对你的类来说是一个可怕的名字,因为它已经是.Net中的内置类:这个问题与Visual Studio应用程序无关,所以我已经删除了这个标记。你必须去掉while循环,当主线程卡在该循环中时,不会触发任何事件。所以计数永远不会增加,循环会停止eps将永远循环。您已经有了该计时器,还可以使用它来停止声音。将sp设为form类的变量。@HansPassant通过这样做,声音将被完整播放。SoundPlayer sp=new SoundPlayer(fileToPlay);sp.Play();if(count>=im.noteDuration){timer1.Enabled=false;sp.Stop();}非常感谢@Idle(请注意,此操作非常有效!