2011-03-10 39 views
0

我想建立一個樣本,發送一個非常短的句子(少於100個字符)谷歌tts服務,返回一個音頻流。我試圖將這個流保存到一個文件中,但是當打開它時,Buf在寫入以下文件後,我可以在真實播放器中打開它,但它只能發出第一個字母(發送給谷歌的第一個字母)。在保存文件時可能會有問題,我從來沒有在代碼中處理過音頻,所以請看看並提出一些更好的代碼。C# - 使用谷歌TTS服務保存音頻文件

WebRequest request = WebRequest.Create(string.Format("http://translate.google.com/translate_tts?q={0}", Uri.EscapeUriString(textBox1.Text.Trim()))); 
      request.Method = "GET"; 

      try 
      { 
       WebResponse response = request.GetResponse(); 

       if (response != null && response.ContentType.Contains("audio")) 
       { 
        Stream stream = response.GetResponseStream(); 

        byte[] buffer = new byte[response.ContentLength]; 

        stream.Read(buffer, 0, (int)response.ContentLength); 

        FileStream localStream = new FileStream("audio.mp3", FileMode.OpenOrCreate); 

        localStream.Write(buffer, 0, (int)response.ContentLength); 

        stream.Close(); 
        localStream.Close(); 
       } 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 

回答

2

也許你需要循環,而從響應流中讀取:

int read = 0; 

while (read < response.ContentLength) 
{ 
    read += stream.Read(buffer, 0, (response.ContentLength - read)); 
} 
+1

我的錯我剛發現發佈這個問題後,無論如何答案表示讚賞。 – 2011-03-10 11:53:40

1

嘗試使用WebClient.DownloadFile代替 - 這是一個單行方法調用,微軟採取了文件的處理你的照顧。如果這不起作用,那麼你至少可以排除你的字節緩衝區處理...

1

我會盡量不依賴於response.ContentLength,你可以使用StreamReader.ReadToEnd()來代替。

0

這適用於我:

WebClient wc = new WebClient();

//如果未添加UserAgent標頭,則會將特殊字符(例如ü讀作「未知字符」) wc.Headers.Add(HttpRequestHeader.UserAgent,「Mozilla/4.0(compatible; MSIE 7.0; Windows NT 5.1 ; .NET CLR 2.0.50727)「);

byte [] mp3Bytes = wc.DownloadData(「http://translate.google.com/translate_tts?tl=de & q = Hallo Welt!」); string fileOut =「audio.mp3」; FileStream fs = new FileStream(fileOut,FileMode.Create); fs.Write(mp3Bytes,0,(int)mp3Bytes.Length); fs.Close();

相關問題