【C#语音文字互转】C#语音转文字(方法一)

Whisper.NET开源项目:https://github.com/sandrohanea/whisper.net/tree/main

一. 环境准备

在VS中安装 Whisper.net,在NuGet包管理器控制台中运行以下命令:

Install-Package Whisper.net
Install-Package Whisper.net.Runtime

其中运行时包 Whisper.net.Runtime 包含本机whisper.cpp库,它是运行 Whisper.net 所必需的。

huggingface下载预训练的Ggml模型。
中等模型及以上效果较好,模型越大越消耗性能

二. 项目示例

准备一段wav格式的音频,运行下面示例

using System;
using System.IO;
using Whisper.net;

namespace ConsoleWhisperTranscription
{
    
    
    class Program
    {
    
    
        static async Task Main(string[] args)
        {
    
    

            // 检查命令行参数中是否包含音频文件路径
            if (args.Length == 0)
            {
    
    
                Console.WriteLine("Please provide the path to the audio file.");
                return;
            }

            string audioFilePath = args[0]; // 从命令行参数获取音频文件路径

            // 确保文件存在
            if (!File.Exists(audioFilePath))
            {
    
    
                Console.WriteLine("The audio file does not exist.");
                return;
            }

            // 初始化Whisper工厂和处理器
            var whisperFactory = WhisperFactory.FromPath("C:\\Users\\26366\\source\\repos\\whisperDemo\\whisperDemo\\ggml-medium.bin");
            var processor = whisperFactory.CreateBuilder()
                .WithLanguage("zh") // 设置识别的语言为中文
                .Build();

            try
            {
    
    
                // 读取音频文件
                using var audioStream = File.OpenRead(audioFilePath);

                // 处理音频文件并输出结果
                Console.WriteLine("Transcribing audio file...");
                await foreach (var result in processor.ProcessAsync(audioStream, default))
                {
    
    
                    Console.WriteLine($"{
      
      result.Start}->{
      
      result.End}: {
      
      result.Text}");
                }
            }
            catch (Exception ex)
            {
    
    
                Console.WriteLine($"An error occurred: {
      
      ex.Message}");
            }
        }


    }
}

效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45906972/article/details/140930123