Search code examples
c#speech-recognitiontext-to-speechspeechsynthesizer

How can I make the SpeechSynthesizer speak through a particular device?


I am new to the Speech Recognition, so please excuse me if the question is very basic level.

My application captures what I speak through my microphone. I have written some responses using my c# code for every command I say and the SpeechSynthesizer does this without any issues using the code mentioned below. But I want the SpeechSynthesizer to respond back through my laptop speaker, rather than my default input device (my microphone). Is it doable?

The code I am currently using is given below. I am looking for something which can get all the playback devices available and then select and speak back using my speaker.

public void SpeakTheText(string text)
{
    SpeechInput = text;
    SpeechSynthesizer _synthesizer = new SpeechSynthesizer();
    _synthesizer.SelectVoiceByHints(VoiceGender.Male);
    _synthesizer.SetOutputToDefaultAudioDevice();//Microphone
    _synthesizer.SpeakAsync(SpeechInput);                       
}

Solution

  • You could use the System.Media.SoundPlayer class to output the audio from a stream. See this example from MSDN

    public void SpeakTheText(string text)
    {  
        // Initialize a new instance of the speech synthesizer.  
        using (SpeechSynthesizer synth = new SpeechSynthesizer())  
        using (MemoryStream streamAudio = new MemoryStream())  
        {  
            // Create a SoundPlayer instance to play the output audio file.  
            System.Media.SoundPlayer m_SoundPlayer = new System.Media.SoundPlayer();  
            // Set voice to male
            synth.SelectVoiceByHints(VoiceGender.Male);
            // Configure the synthesizer to output to an audio stream.  
            synth.SetOutputToWaveStream(streamAudio);  
    
            // Speak a phrase.  
            synth.Speak(text);  
            streamAudio.Position = 0;  
            m_SoundPlayer.Stream = streamAudio;  
            m_SoundPlayer.Play();  
    
            // Set the synthesizer output to null to release the stream.   
            synth.SetOutputToNull();  
    
            // Insert code to persist or process the stream contents here.  
        }
    }
    

    I'm not sure if SoundPlayer can specify an output device, but it should output using your default output device.