我想用线程开起音乐,但怎么能让它停止呢

yinjianjing 2010-09-13 05:52:38
我现在的问题就是无论如何,只要用线程开起的音乐,就关闭不了音乐播放,应该怎么办呢,

以下是测试代码
Audio a;
Thread t;
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(abc));

t.Start();
a = new Audio();

}
private void abc()
{
while (true)
{
a.Play(@"F:\TT\ZhiLi\ZhiLi\ZhiLi\bin\Debug\wav\2-5.wav");

Thread.Sleep(50);
}
}

private void button3_Click(object sender, EventArgs e)
{
a.Stop();

}

音乐类
public class Audio
{
[DllImport("winmm.dll")]
private static extern int mciSendString
(
string lpstrCommand,
string lpstrReturnString,
int uReturnLength,
int hwndCallback
);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetShortPathName
(
[MarshalAs(UnmanagedType.LPTStr)] string path,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,
int shortPathLength
);

public Audio()
{

}

public void Play(string FileName)
{
StringBuilder shortPathTemp = new StringBuilder(255);
int result = GetShortPathName(FileName, shortPathTemp, shortPathTemp.Capacity);
string ShortPath = shortPathTemp.ToString();

mciSendString("open " + ShortPath + " alias song", "", 0, 0);

mciSendString("play song", "", 0, 0);
}

public void Stop()
{
mciSendString("stop song", "", 0, 0);
mciSendString("close song", "", 0, 0);
}

public void Pause()
{
mciSendString("pause song", "", 0, 0);
}

public void Close()
{
mciSendString("close song", "", 0, 0);
}
}



我现在的需求是我想FORM窗口初始化的时候,边创建控件边播放音乐,如果不用线程的话它只会播放完音乐后才能显示界面

如何我必须要用线程怎么办呢
...全文
347 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Felix_ZF1986 2010-12-22
  • 打赏
  • 举报
回复
我也遇到这个问题了,到底要怎么解决啊?
周药师 2010-09-13
  • 打赏
  • 举报
回复
直接把线程关了
bloodish 2010-09-13
  • 打赏
  • 举报
回复

AutoResetEvent stopEvent = new AutoResetEvent(false);
private void abc()
{
while (!stopEvent.WaitOne(50))
{
a.Play(@"F:\TT\ZhiLi\ZhiLi\ZhiLi\bin\Debug\wav\2-5.wav");
}
}
public void Close()
{
stopEvent.Set();
}
Rain_Franklin 2010-09-13
  • 打赏
  • 举报
回复
真的学习了。...~~~
volunteergg 2010-09-13
  • 打赏
  • 举报
回复
3楼正解,关掉线程,在适当的地方加t.Abort(),建议把线程创建及线程对象都封装到音乐类里面
li45214521 2010-09-13
  • 打赏
  • 举报
回复
while (true)
{
if(isPlay)
{
a.Play(@"F:\TT\ZhiLi\ZhiLi\ZhiLi\bin\Debug\wav\2-5.wav");
}
if(isStop)
{
a.Stop();
break;
}
Thread.Sleep(50);
}
zilong4460072 2010-09-13
  • 打赏
  • 举报
回复
关掉那个线程a .Abort();
yinjianjing 2010-09-13
  • 打赏
  • 举报
回复
while (true)
你是说这个用变量吗,没用,我试过了
龍月 2010-09-13
  • 打赏
  • 举报
回复
给 死循环 加个 bool 变量 来判断时候停止
stop 里面改变变量

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧