Wavelength over time

I have a simple code generating a wave file using TTS and then playing it:

public void TestSpeech() { SpeechSynthesizer synth = new SpeechSynthesizer(); using (MemoryStream stream = new MemoryStream()) { synth.SetOutputToWaveStream(stream); synth.Speak("Hello world"); stream.Seek(0, SeekOrigin.Begin); IWaveSource source = new WaveFileReader(stream); EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); var soundOut = new WasapiOut(); soundOut.Initialize(source); soundOut.Stopped += (s, e) => waitHandle.Set(); soundOut.Play(); waitHandle.WaitOne(); soundOut.Dispose(); source.Dispose(); } } 

Everything works fine, but I want to know, before I start playing the wave file, how long it will last. Is there a way to calculate this, or is it available somewhere?

If it is available somewhere, how is it calculated? I assume this is due to the amount of data in the stream, but how?

+7
source share
3 answers

You can use CSCore or NAudio :

CSCore (extracted from this example , the current playback position and total duration are used here ):

 using System; using CSCore; using CSCore.Codecs.WAV; IWaveSource wavSource = new WaveFileReader(stream); TimeSpan totalTime = wavSource.GetLength(); 

NAudio

 using System; using NAudio.Wave; using (var wfr = new WaveFileReader(stream)) { TimeSpan totalTime = wfr.TotalTime; } 

Also see the MSDN docs for TimeSpan .

Duration is calculated from the total length of WAVE data (which can be an estimate for compressed files) and average bytes per second (according to NAudio source in the TotalTime property):

 totalTimeInSeconds = LengthInBytes / AverageBytesPerSecond; 
+3
source
 using CSCore; IWaveSource waveSource = new WaveFileReader(stream); TimeSpan totalTime = waveSource.GetLength( ); //get length returns a timespan 
0
source

In case someone is looking for a workaround, I processed it as follows: (sorry for my first StackOverflow comment)

  1. I created bool mouseScrewsAround = false
  2. a timer event that changes the position of the trackBar during playback only fires if! mouseScrewsAround
  3. trackBar_MouseDown โ†’ mouseScrewsAround = true
  4. trackBar_MouseUp โ†’ change track position, then mouseScrewsAround = false
0
source

All Articles