C#實(shí)現(xiàn)中文錄音文件轉(zhuǎn)為文本文字
我們有一個(gè)中文錄音文件.mp3格式或者是.wav格式,如果我們想要提取錄音文件中的文字內(nèi)容,我們可以采用以下方法,不需要使用Azure Speech API 密鑰注冊(cè)通過(guò)離線的方式實(shí)現(xiàn)。
1.首先我們先在NuGet中下載兩個(gè)包 NAudio 2.2.1、Whisper.net 1.7.3


2.另外我們還需要從Hugging Face網(wǎng)址中下載一個(gè) ggml-medium.bin 文件

3. 代碼部分,由于我們Whisper模型只支持16KHz的語(yǔ)音文件

所以我們要把不同音頻格式的文件統(tǒng)一轉(zhuǎn)為16000Hz的音頻數(shù)據(jù)文件,如下是具體代碼:
using NAudio.Wave;
using System;
public class AudioResampler
{
public static void ConvertTo16kHz(string inputFile, string outputFile)
{
// 打開(kāi)原始音頻文件
using (var reader = new WaveFileReader(inputFile))
{
// 創(chuàng)建目標(biāo)音頻格式 16kHz,單聲道,16位
var targetFormat = new WaveFormat(16000, 1); // 16000Hz, Mono, 16-bit
// 創(chuàng)建轉(zhuǎn)換流,使用 WaveFormatConversionStream 進(jìn)行重采樣
using (var conversionStream = new WaveFormatConversionStream(targetFormat, reader))
{
// 將轉(zhuǎn)換后的音頻數(shù)據(jù)寫(xiě)入新文件
WaveFileWriter.CreateWaveFile(outputFile, conversionStream);
Console.WriteLine("文件已轉(zhuǎn)換為 16kHz 格式");
}
}
}
}
// 使用示例
class Program
{
static void Main(string[] args)
{
string inputFile = @"path_to_input_file.wav"; // 輸入文件路徑
string outputFile = @"path_to_output_file_16kHz.wav"; // 輸出文件路徑
AudioResampler.ConvertTo16kHz(inputFile, outputFile);
}
}4.接下來(lái)是詳細(xì)的具體代碼
public async Task Analyze()
{
//模型
string modelFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ggml-medium-q8_0.bin");
// 初始化Whisper工廠和處理器
var whisperFactory = WhisperFactory.FromPath(modelFilePath);
var processor = whisperFactory.CreateBuilder()
.WithLanguage("zh") // 設(shè)置識(shí)別的語(yǔ)言為中文
.Build();
try
{
string audioFileName = "path_to_output_file_16kHz.wav";
string audioFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, audioFileName);
// 讀取音頻文件
using var audioStream = File.OpenRead(audioFilePath);
// 處理音頻文件并輸出結(jié)果
Console.WriteLine("Transcribing audio file...");
await foreach (SegmentData result in processor.ProcessAsync(audioStream, default))
{
Console.WriteLine($"{result.Start}->{result.End}: {result.Text}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
Console.WriteLine("Press any key to exit...");
}其中需要注意的是 ggml-medium-q8_0.bin文件的絕對(duì)路徑,此文件的獲取方式上述已說(shuō)明。
string modelFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ggml-medium-q8_0.bin");
到此這篇關(guān)于C#實(shí)現(xiàn)中文錄音文件轉(zhuǎn)為文本文字的文章就介紹到這了,更多相關(guān)C#錄音轉(zhuǎn)文本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于C#結(jié)構(gòu)體 你需要知道的
這篇文章主要介紹了關(guān)于C#結(jié)構(gòu)體的相關(guān)知識(shí),以及使用方法,文中代碼非常詳細(xì),幫助大家更好的參考和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06
Unity UGUI通過(guò)搖桿控制角色移動(dòng)
這篇文章主要為大家詳細(xì)介紹了Unity3D基于陀螺儀實(shí)現(xiàn)VR相機(jī)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
基于Kubernetes實(shí)現(xiàn)前后端應(yīng)用的金絲雀發(fā)布(兩種方案)
這篇文章主要介紹了基于Kubernetes實(shí)現(xiàn)前后端應(yīng)用的金絲雀發(fā)布,文中給大家提到了兩種常用方案,通過(guò)示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-12-12

