c# 即時錄音送至openai whisper 翻譯/逐字稿

最近試著做即時翻譯這件事,透過安裝naudio。把麥克風聲音錄下後,每10秒轉成一個檔案上傳至open AI whisper做即時翻譯或逐字稿:


private const string API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private const string API_URL = "https://api.openai.com/v1/audio/transcriptions";
var waveIn = new WaveInEvent();
waveIn.WaveFormat = new WaveFormat(16000, 1);

var buffer = new MemoryStream();
var writer = new WaveFileWriter(buffer, waveIn.WaveFormat);

//var writer = new WaveFileWriter(new DisposeStream(buffer), waveIn.WaveFormat);

waveIn.DataAvailable += async (sender, e) =>
{
writer.Write(e.Buffer, 0, e.BytesRecorded);
if (buffer.Length > 16000 * 2 * 10) // 每10秒
{
var audioData = buffer.ToArray();
buffer.SetLength(0);
buffer.Position = 0;
await SaveAudioChunkAsMp3(audioData, waveIn.WaveFormat);
await SendAudioChunk(audioData);
}
};

Console.WriteLine(“開始錄音。按任意鍵停止…”);
waveIn.StartRecording();
Console.ReadKey();

waveIn.StopRecording();
writer.Dispose();
buffer.Dispose();

static async Task SendAudioChunk(byte[] audioData)
{
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add(“Authorization”, $”Bearer {API_KEY}”);

using var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(audioData), “file”, “audio.wav”);
content.Add(new StringContent(“whisper-1”), “model”);
content.Add(new StringContent(“language”), “zh-hant”);

var response = await httpClient.PostAsync(API_URL, content);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine($”Transcription: {result}”);
}

作者: 林壽山

林壽山 目前任職於軟體公司研究開發部門主管,主要採用.net core/.net 5/6 開發,收銀機pos系統開發,第三方支付設計(綠界、馬來西亞epay/happypay、台新one碼),金流設計,行動支付設計(悠遊卡/一卡通),支付寶,微信,街口支付,信用卡機(聯合信用卡),擅長PHP網頁設計(CodeIgniter、Laravel)框架、Delphi程式設計、資料庫設計、C# WinForm/WebForm程式設計、ASP.net MVC、LINE串接、API串接設計