簡體   English   中英

使用HttpClient和PushStreamContent將實時音頻文件發送到REST服務器

[英]Sending live audio file to REST server using HttpClient and PushStreamContent

我需要將音頻數據從麥克風傳輸到REST服務器。

我正在使用專有的ASR引擎,並且需要收集數據,然后在一次調用PostAsync的過程中實時進行流傳輸。在網上,我在PushStreamContent上找到了文章,但是要么我沒有正確使用它,要么我不明白我的意思。我在做(或兩者都做)。

我有一個稱為stream_memory的MemoryStream,我從主線程不斷向其中寫入數據,並且想在數據流傳輸時讀取它,並實時將其發布在單個帖子中。 在下面的示例中,我還使用事件stream_data_event和對象鎖來防止多個線程同時寫入MemoryStream。 每次讀取時都會清除內存流,因為以后不需要數據。

這是在自己的線程中運行的代碼片段:

http_client = new HttpClient();
http_client.http_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language", "en-us");
http_client.DefaultRequestHeaders.TransferEncodingChunked = true;
HttpContent content = new System.Net.Http.PushStreamContent(async (stream, httpContent, transportContext) =>
            {
                while (stream_data_event.WaitOne())
                {

                    lock (main_window.stream_memory_lock)
                    {
                        stream_data_event.Reset();
                        long write_position = main_window.stream_memory.Position;
                        main_window.stream_memory.Seek(0, SeekOrigin.Begin);
                        main_window.stream_memory.CopyTo(stream, (int)write_position);
                        main_window.stream_memory.Position = 0;
                    }
                }
            });
content.Headers.TryAddWithoutValidation("Content-Type", "audio/L16;rate=8000");
string request_uri = String.Format("/v1/speech:recognize");

HttpResponseMessage response = await http_client.PostAsync(request_uri, content);
string http_result = await response.Content.ReadAsStringAsync();

對PostAsync的調用按預期方式調用PushStreamContent的代碼。 但是,只要我處於while循環中,什么都不會發送到服務器(在wireshark中檢查)。 如果我在調試器中手動退出循環並在流上調用close,則PostAsync存在,但沒有任何內容發送到服務器。

我需要一種方法可以在PostAsync中繼續流信息,並在音頻到達時使數據消失。

有任何想法嗎?

事實證明,未發送到服務器的原因與wireshark顯示HTTP結果的方式有關。 我的期望是,一旦發送了請求,我將立即在Wireshark中看到它。 但是,wireshark僅在請求完成后才顯示請求,這意味着在請求開始流式傳輸之后很久才顯示該請求。

意識到這一點之后,我可以看到數據被發送到服務器了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM