using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Recognition;//引用系统的Speech的识别
using System.Speech.Synthesis; //引用语音合成 
namespace ConsoleApplication1
{
    class Program
    {
        static SpeechSynthesizer sy = new SpeechSynthesizer();
        public static void Main2()
        {
            //创建中午识别器
            using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("zh-CN")))
            {
                //----------------
                //初始化命令词
                Choices conmmonds = new Choices();
                //添加命令词
                conmmonds.Add(new string[] { "你好", "你是谁", "很高兴见到你", "再见", "你" });
                //初始化命令词管理
                GrammarBuilder gBuilder = new GrammarBuilder();
                //将命令词添加到管理中
                gBuilder.Append(conmmonds);
                //实例化命令词管理
                Grammar grammar = new Grammar(gBuilder);
                //-----------------

                //创建并加载听写语法(添加命令词汇识别的比较精准)
                recognizer.LoadGrammar(grammar);
                //为语音识别事件添加处理程序。
                recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRRecongized);
                //将输入配置到语音识别器。
                recognizer.SetInputToDefaultAudioDevice();
                //启动异步,连续语音识别。
                recognizer.RecognizeAsync(RecognizeMode.Multiple);

                //保持控制台窗口打开。
                while (true)
                {
                    Console.ReadLine();
                }

            }
        }


        //speechrecognized事件处理
        static void recognizer_SpeechRRecongized(object sender, SpeechRecognizedEventArgs e)
        {
            Console.WriteLine("识别结果:" + e.Result.Text);
            sy.Speak(e.Result.Text);
        }
    }
}

录音,使用其他库,操作字节

using System;
using NAudio.Wave;

class AudioRecorder
{
    private WaveInEvent waveIn; // 录音设备
    private WaveFileWriter writer; // 写入音频文件
    private string outputFilePath; // 保存路径

    // 开始录音
    public void StartRecording(string filePath)
    {
        outputFilePath = filePath;

        // 初始化录音设备(默认麦克风)
        waveIn = new WaveInEvent();
        waveIn.WaveFormat = new WaveFormat(44100, 1); // 44.1kHz,单声道

        // 当有音频数据时,写入文件
        waveIn.DataAvailable += (s, e) =>
        {
            writer?.Write(e.Buffer, 0, e.BytesRecorded);
        };

        // 创建文件写入器
        writer = new WaveFileWriter(outputFilePath, waveIn.WaveFormat);

        // 开始录音
        waveIn.StartRecording();
        Console.WriteLine("开始录音...");
    }

    // 停止录音
    public void StopRecording()
    {
        if (waveIn == null) return;

        waveIn.StopRecording();
        Console.WriteLine("停止录音");

        // 释放资源
        writer?.Dispose();
        waveIn?.Dispose();
        writer = null;
        waveIn = null;

        Console.WriteLine($"录音已保存至:{outputFilePath}");
    }

    // 测试示例
    static void Main()
    {
        var recorder = new AudioRecorder();

        // 开始录音(保存到当前目录的recording.wav)
        recorder.StartRecording("recording.wav");

        Console.WriteLine("按任意键停止录音...");
        Console.ReadKey();

        // 停止录音
        recorder.StopRecording();
    }
}

字节转音频输出

using NAudio.Wave;
using System;
using System.IO;

public class ByteAudioPlayer
{
    /// <summary>
    /// 播放 PCM 格式的字节数组声音
    /// </summary>
    /// <param name="audioBytes">PCM 音频字节数组</param>
    /// <param name="sampleRate">采样率(如 16000、44100)</param>
    /// <param name="bitsPerSample">位深度(如 16、8)</param>
    /// <param name="channels">声道数(1=单声道,2=立体声)</param>
    public void Play(byte[] audioBytes, int sampleRate = 16000, int bitsPerSample = 16, int channels = 1)
    {
        if (audioBytes == null || audioBytes.Length == 0)
        {
            throw new ArgumentException("音频字节数组不能为空");
        }

        // 创建内存流包装字节数据
        using (var memoryStream = new MemoryStream(audioBytes))
        // 创建原始音频流(指定 PCM 格式)
        using (var waveStream = new RawSourceWaveStream(memoryStream, 
            new WaveFormat(sampleRate, bitsPerSample, channels)))
        // 使用 WaveOutEvent 作为音频输出设备
        using (var waveOut = new WaveOutEvent())
        {
            try
            {
                // 初始化输出设备
                waveOut.Init(waveStream);
                // 开始播放
                waveOut.Play();

                // 等待播放完成(循环检查播放状态)
                while (waveOut.PlaybackState == PlaybackState.Playing)
                {
                    System.Threading.Thread.Sleep(50);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"播放失败: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 从文件读取字节并播放(测试用)
    /// </summary>
    public void PlayFromFileBytes(string filePath, int sampleRate = 16000, int bitsPerSample = 16, int channels = 1)
    {
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException("文件不存在", filePath);
        }

        // 读取文件字节
        byte[] audioBytes = File.ReadAllBytes(filePath);
        // 播放字节数据
        Play(audioBytes, sampleRate, bitsPerSample, channels);
    }
}

// 使用示例
class Program
{
    static void Main(string[] args)
    {
        var player = new ByteAudioPlayer();
        
        try
        {
            // 示例1:播放 PCM 字节数组(这里生成一段测试音频)
            byte[] testAudio = GenerateTestAudio(
                frequency: 1000,    // 1000Hz 声音
                durationMs: 2000,   // 持续2秒
                sampleRate: 16000   // 16000采样率
            );
            player.Play(testAudio, 16000, 16, 1);

            // 示例2:播放 PCM 文件的字节(替换为你的 PCM 文件路径)
            // player.PlayFromFileBytes(@"C:\test.pcm", 16000, 16, 1);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    // 生成测试用的 PCM 音频字节(16位单声道)
    static byte[] GenerateTestAudio(int frequency, int durationMs, int sampleRate)
    {
        int sampleCount = (int)(sampleRate * durationMs / 1000.0);
        short[] samples = new short[sampleCount];
        double amplitude = 32760; // 16位最大振幅(避免溢出)

        for (int i = 0; i < sampleCount; i++)
        {
            // 生成正弦波
            double time = (double)i / sampleRate;
            samples[i] = (short)(amplitude * Math.Sin(2 * Math.PI * frequency * time));
        }

        // 转换为字节数组(16位 = 2字节/样本)
        byte[] bytes = new byte[samples.Length * 2];
        Buffer.BlockCopy(samples, 0, bytes, 0, bytes.Length);
        return bytes;
    }
}

更多推荐