c#でmp3を鳴らす
c#からmp3を鳴らす方法のうち、MCIsendStringを使う方法。play後にはちゃんとstopしてcloseしとかないと次鳴らせないので、playにnotifyをつけてWndProcで再生終了を受け取るのがポイント。これはFormで作ったからいいけど、[STAThread]じゃないと動かない模様。
public partial class mainform : Form
{
[System.Runtime.InteropServices.DllImport("winmm.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern int mciSendString(string command, System.Text.StringBuilder buffer, int bufferSize, IntPtr hwndCallback);
string musicFile = "";
string aliasName = "MediaFile";
public mainform()
{
InitializeComponent();
}
private void mainform_Load(object sender, EventArgs e)
{
musicFile = "test.mp3";
}
private void button1_Click(object sender, EventArgs e)
{
string cmd;
cmd = "open "" + musicFile + "" type mpegvideo alias " + aliasName;
if (mciSendString(cmd, null, 0, IntPtr.Zero) != 0)
{
return;
}
cmd = "play " + aliasName + " notify";
mciSendString(cmd, null, 0, this.Handle);
}
private static int MM_MCINOTIFY = 0x3B9;
private static int MCI_NOTIFY_SUCCESSFUL = 1;
protected override void WndProc(ref Message m)
{
if (m.Msg == MM_MCINOTIFY) {
if ((int)m.WParam == MCI_NOTIFY_SUCCESSFUL) {
string cmd;
cmd = "stop " + aliasName;
mciSendString(cmd, null, 0, IntPtr.Zero);
cmd = "close " + aliasName;
mciSendString(cmd, null, 0, IntPtr.Zero);
}
}
base.WndProc(ref m);
}
}