Play wav using HTML5

I am trying to put the text into the speech of a wav file and play it with the HTML5 <audio> . The text-to-speech method outputs bytes, but the html5 control does not play it.

If instead of streaming bytes directly to the control, I first save it as a file, and then convert the file to bytes with a file stream and output it, it starts to play, but I do not want to save the file every time. I am using MVC 4.

  // in a class library public byte[] GenerateAudio(string randomText) { MemoryStream wavAudioStream = new MemoryStream(); SpeechSynthesizer speechEngine = new SpeechSynthesizer(); speechEngine.SetOutputToWaveStream(wavAudioStream); speechEngine.Speak(randomText); wavAudioStream.Flush(); Byte[] wavBytes = wavAudioStream.GetBuffer(); return wavBytes; } // in my controller public ActionResult Listen() { return new FileContentResult(c.GenerateAudio(Session["RandomText"].ToString()), "audio/wav"); } // in my view <audio controls autoplay> <source src="@Url.Content("~/Captcha/Listen")" type="audio/wav" /> Your browser does not support the <audio> element. </audio> 
+4
source share
1 answer

I also play the wav file for the audio element, and your code has the same logic as mine. I just noticed that you are flushing your stream before returning an array of bytes that will seem empty.

In addition, you can use the file as a return type and pass an array of bytes to its constructor. The content type is the same as in your code. I would like to mention (maybe this can help too) that I used 2 streams: the stream of the external area and the actual stream in which the data will be stored. After I populated the actual stream, I copied its contents to the external stream using stream.CopyTo() , and the instance of this external stream is the one I used in my return statement. This avoids the error "Unable to access the closed stream" (not an exact error statement).

0
source

Source: https://habr.com/ru/post/1412355/


All Articles