0

I am trying to build a sample which send a very short sentence (less than 100 char) google tts service which returns a audio stream. I am trying to save this stream into a file but when open it, Buf after writing following file, i am able to open it in real player but it only utters first letter (first letter of the sentence sent to google tts). There might be a problem in saving file, I never dealt with Audio in Code so please take a look and suggest some better code.

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);
            }
Mubashar
  • 12,300
  • 11
  • 66
  • 95

4 Answers4

2

Maybe you need to loop while reading from the response stream:

int read = 0;

while ( read < response.ContentLength )
{
    read += stream.Read(buffer, 0, ( response.ContentLength - read ) );
}
Nick
  • 25,026
  • 7
  • 51
  • 83
1

Try using WebClient.DownloadFile instead - it's a one line method call where microsoft take care of the file handling for you. If that doesn't work, then you can at least rule out your byte buffer processing...

Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
1

I would try not relying on response.ContentLength, you could use StreamReader.ReadToEnd() instead.

yms
  • 10,361
  • 3
  • 38
  • 68
0

This works for me:

WebClient wc = new WebClient();

//If UserAgent header is not added, then the special chars like ü get pronounced as "unknown character" 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();

user133464
  • 151
  • 1
  • 4