MCI (Media Control Interface) を利用してWaveファイルを再生する - C#
MCI(Media Control Interface)を利用してWaveファイルを再生します。
UI
フォームにボタンを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を開きファイルを選択します。
open "再生するファイル名" alias 識別名
のコマンドを送信しMCIでファイルを開きます。続いて
play 識別名
のコマンドを送信し再生を開始します。
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);
}
再生を停止する場合は
stop 識別名
コマンドで再生を停止し
close 識別名
コマンドでファイルを閉じます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用