MCI(Media Control Interface)を利用してWaveファイルを再生します。
フォームにボタンを2つ、openFileDialogを1つ配置します。
以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SoundDemo
{
public partial class FormMain : Form
{
[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer,
int bufferSize, IntPtr hwndCallback);
public FormMain()
{
InitializeComponent();
}
private void button_MCIPlay_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string cmd;
string IDName="Player01";
cmd = string.Format("open \"{0:s}\" alias {1:s}", openFileDialog1.FileName, IDName);
if (mciSendString(cmd, null, 0, IntPtr.Zero) == 0){
cmd = string.Format("play {0:s}", IDName);
mciSendString(cmd, null, 0, IntPtr.Zero);
}
}
}
private void button_MCIStop_Click(object sender, EventArgs e)
{
string cmd;
string IDName = "Player01";
cmd = string.Format("stop {0:s}", IDName);
mciSendString(cmd, null, 0, IntPtr.Zero);
cmd = string.Format("close {0:s}", IDName);
mciSendString(cmd, null, 0, IntPtr.Zero);
}
}
}
[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer,
int bufferSize, IntPtr hwndCallback);
mciへコマンドを送信するAPI mciSendStringをインポートします。
private void button_MCIPlay_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string cmd;
string IDName="Player01";
cmd = string.Format("open \"{0:s}\" alias {1:s}", openFileDialog1.FileName, IDName);
if (mciSendString(cmd, null, 0, IntPtr.Zero) == 0){
cmd = string.Format("play {0:s}", IDName);
mciSendString(cmd, null, 0, IntPtr.Zero);
}
}
}
ボタンをクリックすると、openFileDialogを開きファイルを選択します。
のコマンドを送信しMCIでファイルを開きます。続いて
private void button_MCIStop_Click(object sender, EventArgs e)
{
string cmd;
string IDName = "Player01";
cmd = string.Format("stop {0:s}", IDName);
mciSendString(cmd, null, 0, IntPtr.Zero);
cmd = string.Format("close {0:s}", IDName);
mciSendString(cmd, null, 0, IntPtr.Zero);
}
再生を停止する場合は