作者:浪子一品香_938 | 来源:互联网 | 2023-10-11 20:22
做的一个小的MP3播放器,用usingSystem.Windows.Forms.Timer这个来计时,获取当前歌曲播放的位置(播放时间),并显示到窗体上.当我运行程序,点击一首歌曲开始播放时,程序
做的一个小的MP3播放器,用using System.Windows.Forms.Timer这个来计时,获取当前歌曲播放的位置(播放时间),并显示到窗体上.当我运行程序,点击一首歌曲开始播放时,
程序就出现未响应。求解。
下面是一部分代码:
class DoMusic
{
[DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
public static extern int mciSendString(
string lpstrCommand,
string lpstrReturnString,
int uReturnLength,
int hwndCallback
);
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);
///
/// 获取当前播放的位置
///
/// 当前时间值(毫秒)
public string GetCurrentTime()
{
string st="";
mciSendString(@"status song position", st, 100, 0);
return st;
}
public void Play(string path)
{
StringBuilder shortpath = new StringBuilder(80);
int result = GetShortPathName(path, shortpath, shortpath.Capacity);
path = shortpath.ToString();
mciSendString(@"close all", null, 0, 0);
mciSendString(@"open " + path + " alias song", null, 0, 0); //打开
mciSendString(@"play song", null, 0, 0); //播放
}
}
public partial class MyMusic : Form
{
public MyMusic()
{
InitializeComponent();
//Control.CheckForIllegalCrossThreadCalls = false;
}
//播放
private void btnPlay_Click(object sender, EventArgs e)
{
string path = @"F:\Music\123.mp3";
DoMusic dm = new DoMusic();
Play(path);
progressTimer.Start();
}
//Timer事件
private void progressTimer_Tick(object sender, EventArgs e)
{
DoMusic dm = new DoMusic();
string currentTime = dm.GetCurrentTime();
label1.text=currentTime;
}
}
16 个解决方案
string path = @"F:\Music\123.mp3";
DoMusic dm = new DoMusic();
dm.Play(path); progressTimer.Start();
直接可以掉play()吗??
private void btnPlay_Click(object sender, EventArgs e)
{
string path = @"F:\Music\123.mp3";
DoMusic dm = new DoMusic();
Play(path);
progressTimer.Start();
}
在private void btnPlay_Click(object sender, EventArgs e)
这个地方放个断点进去看看,就可知道了啊
播放歌曲可能比较占资源,试一下将计时的方法另开条线程处理
导出函数封装错误!
[DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
public static extern int mciSendString(
string lpstrCommand,
string lpstrReturnString,
int uReturnLength,
int hwndCallback
);
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);
CharSet = CharSet.Auto修改为CharSet.Ansi
建议你也封装好 mciGetErrorString 函数,从此获得mci的错误信息