【发布时间】:2020-09-13 17:52:50
【问题描述】:
如何在计时器中播放声音?还是有其他方法可以做到这一点?我想每 20 分钟播放一次短音。 我的代码可以在计时器中正常显示消息框,也可以通过按钮播放声音。但无法在计时器中播放声音。
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.Runtime.InteropServices;
using System.Media;
namespace Eye
{
public partial class Form1 : Form
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"C:\Users\user\Desktop\Sounds\sound.wav");
public int makroButon;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 6000;
}
private void radioButton1_Checked(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
player.Play();
}
}
}
【问题讨论】:
-
您确定 Timer 确实已启动,
Timer.Tick事件实际上已连接到timer1_Tick处理程序,并且您的声音文件是 PCM wav 格式吗? -
如果我在 timer1_Tick 中放了一个 MessageBox.Show 命令,它就会正常工作。如果我尝试用按钮播放声音,它也在播放。我也尝试在另一个函数中播放它,只是从 timer1_Tick 调用该函数但仍然没有播放。
-
做一个实验:从表单设计器中删除 Timer1 组件及其
Tick处理程序。在player字段定义附近添加System.Windows.Forms.Timer playerTimer = null;。在 Form.Load 中,添加:playerTimer = new System.Windows.Forms.Timer() { Interval = 5000 }; playerTimer.Tick += (o, a) => player.Play(); playerTimer.Start();。启动项目以打开 Form1。 -
我找到了解决方案...此代码不起作用,因为 Form1_load 什么也没做...所以计时器的间隔仍然是 100...我从设计页面更改它并且它工作。谢谢你的回答我的朋友。
标签: c# .net forms winforms timer