获取错误:ReadTimeout = 'stream.ReadTimeout' 在使用 MemoryStream 实例时引发类型为 'System.InvalidOperationException' 的异常

问题描述 投票:0回答:0

具体消息是“此流不支持超时”。我也遇到了类似的异常,但对于 WriteTimeout。 这是我的代码。我正在尝试将音频数据写入 MemoryStream 实例(而不是写入文件并使用 I/O 操作)。最后我想在 POST 请求中发送这个音频数据。

using NAudio.Wave;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Web;
using System.Media;

internal class Program
{
    static WaveInEvent? waveIn;
    private static HttpClient httpClient = new HttpClient();
    static async Task Main(string[] args)
    {
        int deviceNo = GetDeviceNo();

        //starts recording
        MemoryStream stream = new MemoryStream();
        Console.WriteLine("Press any key to start recording...");
        Console.ReadKey();

        waveIn = new WaveInEvent();
        waveIn.DeviceNumber = deviceNo;
        waveIn.WaveFormat = new WaveFormat(44100, 1);
        waveIn.DataAvailable += (sender, e) =>
        {
            stream.Write(e.Buffer, 0, e.BytesRecorded);
        };

        waveIn.StartRecording();
        Console.WriteLine("Recording...");

        Console.ReadKey();
        waveIn.StopRecording();

        Console.WriteLine("Recording stopped.");

        //Transcribing audio file to text using WhisperAI
        var fileContent = new StreamContent(stream);
        var modelContent = new StringContent("whisper-1");

        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "key");

        var whisperCont = new MultipartFormDataContent();
        whisperCont.Add(fileContent, "file", "output.wav");
        whisperCont.Add(modelContent, "model");

        var whisperResponse = await httpClient.PostAsync("https://api.openai.com/v1/audio/transcriptions", whisperCont);
        var whisperRespCont = await whisperResponse.Content.ReadAsStringAsync();

        var whisperRespObj = JsonSerializer.Deserialize<WhisperData>(whisperRespCont);
        string ogText = whisperRespObj.text;
        Console.WriteLine(ogText);

        httpClient.Dispose();
        stream.Dispose();
    }

public class WhisperData
{
    public string text { get; set; }
}

实例化后任何地方都会抛出异常。我已经搜索了答案,但它们不相关或不起作用。如果需要添加更多代码以获得更好的上下文,我将相应地编辑帖子。我对这种记忆的东西没有经验。任何帮助表示赞赏。

c# stream naudio memorystream
© www.soinside.com 2019 - 2024. All rights reserved.