Created
December 1, 2023 05:11
-
-
Save mahiya/3aa6a2e4b34f34be77fa3c5f217e3a78 to your computer and use it in GitHub Desktop.
C# でオーディオデバイスやマイクデバイスからその入出力を録音してファイル出力する処理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dotnet add package NAudio --version 2.2.1 | |
using NAudio.CoreAudioApi; | |
using NAudio.Wave; | |
namespace RecordFromMicAndAudio | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
// マイクデバイスから録音する | |
RecordFromMicDevice("mic.wav", 5); | |
// オーディオデバイスから録音する | |
RecordFromAudioDevice("audio.wav", 5); | |
} | |
/// <summary> | |
/// マイクデバイスから録音する | |
/// </summary> | |
static void RecordFromMicDevice(string outputPath, int recordSeconds) | |
{ | |
// デバイス番号を指定 | |
const int deviceNumber = 0; | |
// 録音とファイル出力のためのインスタンスを作成 | |
using var waveIn = new WaveInEvent(); | |
waveIn.DeviceNumber = deviceNumber; | |
waveIn.WaveFormat = new WaveFormat(44100, WaveInEvent.GetCapabilities(deviceNumber).Channels); | |
// 録音処理を開始する | |
Record(waveIn, outputPath, recordSeconds); | |
} | |
/// <summary> | |
/// オーディオデバイスから録音する | |
/// </summary> | |
static void RecordFromAudioDevice(string outputPath, int recordSeconds) | |
{ | |
// オーディオデバイスの一覧を取得 | |
var devices = new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active); | |
// オーディオデバイスを選択 | |
//var device = devices.First(); | |
var device = devices.Last(); | |
// 録音とファイル出力のためのインスタンスを作成 | |
using var waveIn = new WasapiLoopbackCapture(device); | |
// 録音処理を開始する | |
Record(waveIn, outputPath, recordSeconds); | |
} | |
/// <summary> | |
/// 共通の録音処理 | |
/// </summary> | |
static void Record(IWaveIn waveIn, string outputPath, int recordSeconds) | |
{ | |
var waveWriter = new WaveFileWriter(outputPath, waveIn.WaveFormat); | |
// 録音したバッファの処理を定義 | |
waveIn.DataAvailable += (_, ee) => | |
{ | |
// バッファをファイルに書き込む | |
waveWriter.Write(ee.Buffer, 0, ee.BytesRecorded); | |
waveWriter.Flush(); | |
}; | |
// 録音停止時の処理を定義 | |
waveIn.RecordingStopped += (_, __) => | |
{ | |
// バッファをファイルに書き込む | |
waveWriter.Flush(); | |
}; | |
// 録音開始 | |
Console.WriteLine("Recording Started..."); | |
waveIn.StartRecording(); | |
// 録音するために指定された秒数だけ待機 | |
Thread.Sleep(recordSeconds * 1000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment