非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

C#:音声ファイルの再生

      2015/12/29

ちょっと、音声関係のプログラミングをやろうと思って、まずは手始めに再生と停止だけをする簡単なアプリを作りました。WMAファイルの再生は確認済みです。

参考サイト(ほとんどコピペさせていただきました)
http://dobon.net/vb/dotnet/programing/playmidifile.html

下記がコード前文です。

using System;

using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Text;

class Editor{
   [STAThread]
   static void Main(string[] args){
      Application.Run(new MainWindow(args));
   }
}

partial class MainWindow : Form{

   [System.Runtime.InteropServices.DllImport(“winmm.dll”)]
   private static extern int mciSendString(String command,
      StringBuilder buffer, int bufferSize, IntPtr hwndCallback);

   private string aliasName = “MediaFile”;

   public MainWindow(string[] args){
      this.StartPosition = FormStartPosition.CenterScreen;
      this.Width = 300;
      this.Height =100;
      this.Text = “Sound”;
      this.setComponents();
   }

   private void actionRun(object sender, EventArgs e){
      //再生するファイル名
      string fileName = “C:\***sound.wma”;

      string cmd;
      //ファイルを開く
      cmd = “open “” + fileName + “” type mpegvideo alias “ + aliasName;
      if (mciSendString(cmd, null, 0, IntPtr.Zero) != 0) return;
      //再生する
      cmd = “play “ + aliasName;
      mciSendString(cmd, null, 0, IntPtr.Zero);
   }
   private void actionStop(object sender, EventArgs e){
      string cmd;
      //停止する
      cmd = “stop “ + aliasName;
      mciSendString(cmd, null, 0, IntPtr.Zero);
      //閉じる
      cmd = “close ” + aliasName;
      mciSendString(cmd, null, 0, IntPtr.Zero);
   }

   private void setComponents(){
      Font font = new Font(“Meiryo UI”, 10);

      Button runBtn = new Button(){
         Size = new Size(120, 30),
         Font = font,
         Location = new Point(20, 20),
         Text = “再生”,
         Parent = this,
      };
      runBtn.Click += new EventHandler(actionRun);

      Button stopBtn = new Button(){
         Size = new Size(120, 30),
         Font = font,
         Location = new Point(150, 20),
         Text = “停止”,
         Parent = this,
      };
      stopBtn.Click += new EventHandler(actionStop);
   }
}

スポンサーリンク

 - C#応用編