123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- using System;
-
- using NAudio.Wave;
-
- namespace XHWK.WKTool.Utils
- {
- public class ZAudioRecordHelper
- {
- public enum RecordType
- {
- loudspeaker = 0, // 扬声器
- microphone = 1 //麦克风
- }
-
- public enum RecordState
- {
- stop = 0,
- start = 1,
- pause = 2
- }
-
- //录制的类型
- RecordType _t = RecordType.microphone;
-
- RecordState _state = RecordState.stop;
-
- //录制麦克风的声音
- WaveInEvent waveIn = null; //new WaveInEvent();
- //录制扬声器的声音
- WasapiLoopbackCapture capture = null; //new WasapiLoopbackCapture();
- //生成音频文件的对象
- WaveFileWriter writer = null;
-
- string audioFile = "";
-
- public ZAudioRecordHelper(string filePath,RecordType type)
- {
- _t = type;
- audioFile = filePath;
- }
-
- /// <summary>
- /// 开始录制
- /// </summary>
- public void StartRecordAudio()
- {
- _state = RecordState.start;
- try
- {
- if (_t == RecordType.microphone)
- {
- waveIn = new WaveInEvent();
- writer = new WaveFileWriter(audioFile, waveIn.WaveFormat);
- //开始录音,写数据
- waveIn.DataAvailable += (s, a) =>
- {
- if (_state == RecordState.start) {
- writer.Write(a.Buffer, 0, a.BytesRecorded);
- }
- };
-
- //结束录音
- waveIn.RecordingStopped += (s, a) =>
- {
- writer.Dispose();
- writer = null;
- waveIn.Dispose();
- };
-
- waveIn.StartRecording();
- }
- else
- {
- capture = new WasapiLoopbackCapture();
- writer = new WaveFileWriter(audioFile, capture.WaveFormat);
-
- capture.DataAvailable += (s, a) =>
- {
- if (_state == RecordState.start)
- {
- writer.Write(a.Buffer, 0, a.BytesRecorded);
- }
- };
- //结束录音
- capture.RecordingStopped += (s, a) =>
- {
- writer.Dispose();
- writer = null;
- capture.Dispose();
- };
- capture.StartRecording();
- }
- }
- catch (Exception ex)
- {
- }
- }
-
- /// <summary>
- /// 结束录制
- /// </summary>
- public void StopRecordAudio()
- {
- _state = RecordState.stop;
- if (_t == RecordType.microphone)
- {
- waveIn.StopRecording();
- }
- else
- {
- capture.StopRecording();
- }
- }
-
- /// <summary>
- /// 暂停录制
- /// </summary>
- public void PauseRecordAudio()
- {
- _state = RecordState.pause;
- }
-
- /// <summary>
- /// 恢复录制
- /// </summary>
- public void ResumeRecordAudio() {
- _state = RecordState.start;
- }
- }
- }
|