録音
VC#2015 デスクトップで音声録音をやろうと思ったのですが、簡単にできると思っていたのに意外と時間がかかったので覚え書き (^◇^)
基本的には
http://csharp-tricks-en.blogspot.jp/2010/09/record-sound-from-microphone.html
のサイトのパクリです。
起動引数に録音時間、ファイル名、フォルダーを指定
長いパスとかスペースの入ったフルパスファイル名は
mciSendString("save recsound " + ファイル名
で失敗するみたいです。細かいことは詳しい人に任せてカレントパスにファイル書き込み後ファイル移動にて対応(後ろ向き・・・)
最初は外部プログラムにしたけどCPU負荷が低かったので本体プログラムに取り込んでしまい不用品となりました。
実は音声→テキスト変換をやろうと思ってた(^◇^)
以下プログラム
public partial class Form1 : Form
{
[DllImport("winmm.dll")]
private extern static int mciSendString(string s1, StringBuilder s2, int i1, int i2);
public Form1()
{
InitializeComponent();
string[] cmds = System.Environment.GetCommandLineArgs();
int i = 0;
//コマンドライン引数を列挙する
foreach (string cmd in cmds)
{
Console.WriteLine(cmd);
if (i == 1) numericUpDown1.Value = int.Parse(cmds[1]);
if (i == 2) textBox1.Text = cmds[2];
if (i == 3) textBox2.Text = cmds[3];
i++;
}
if (textBox1.Text == "")
{
textBox1.Text = "test_Rec.wav";
if (System.IO.Directory.Exists(@"c:\sound") == false) System.IO.Directory.CreateDirectory(@"c:\sound");
}
if (textBox2.Text == "")textBox2.Text = @"c:\sound";
if (System.IO.Directory.Exists(textBox2.Text) == false) System.IO.Directory.CreateDirectory(textBox2.Text);
// タイマー生成
timer1.Tick += new EventHandler(this.OnTick_FormsTimer1);
timer1.Interval = 1000 * (int)numericUpDown1.Value;
rec_start();
// タイマーを開始
timer1.Start();
}
public void OnTick_FormsTimer1(object sender, EventArgs e)
{
button2_Click(sender, e);
timer1.Stop();// タイマーを停止
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
rec_start();
}
private void rec_start()
{ // 録音開始
button1.Enabled = false;
button1.Text = "録音中";
button1.BackColor = Color.Red;
mciSendString("open new Type waveaudio Alias recsound", null, 0, 0);
mciSendString("record recsound", null, 0, 0);
}
private void button2_Click(object sender, EventArgs e)
{ // 録音停止
string fileName;// = @"C:\Users\maki\Desktop\test_Rec.wav";
fileName = textBox1.Text;// フルパスで記載できるが長い名前、スペースがあると失敗するみたい。パスがないとカレントフォルダーに作る
//fileName= "test_Rec.wav";
mciSendString("save recsound " + fileName , null, 0, 0);
mciSendString("close recsound", null, 0, 0);
System.Threading.Thread.Sleep(500);
if(System.IO.File.Exists(textBox2.Text + "\\" + fileName) == false)System.IO.File.Move(fileName, textBox2.Text+"\\"+ fileName);
}