Search code examples
c#windowsaudiouwpmedia

Unable to control volume using MediaElement.Volume property


I'm trying to control the MediaElement volume level and increment it whenever I call the IncreaseVolume method. When it reaches the maximum volume I want to reset it back to the lowest volume setting. I'm noticing however that changing the volume property does nothing to the volume on playback when I call the TextToSpeech method, even though the MediaElement volume property does get set to the new value. What am I doing wrong here? Code is below:

    private static readonly MediaElement MediaElement = new MediaElement();
    private static readonly SpeechSynthesizer Synthesizer = new SpeechSynthesizer();

    public static async void TextToSpeech(string text)
    {
        var stream = await Synthesizer.SynthesizeTextToStreamAsync(text);
        MediaElement.SetSource(stream, stream.ContentType);
        MediaElement.Play();
    }

    public static void IncreaseVolume()
    {
        if (MediaElement.Volume >= 1)
        {
            TextToSpeech("Max volume reached");
            MediaElement.Volume = 0.1;
        }

        MediaElement.Volume += 0.1;
        TextToSpeech("New volume is " + MediaElement.Volume);
    }

Solution

  • I'm noticing however that changing the volume property does nothing to the volume on playback when I call the TextToSpeech method

    Please try to add the MediaElement to current page's Visual Tree, or in other words, you need to add the MediaElement as a child of the page. The Volume works only when the MediaElement is in the Visual Tree.

    Need something like this:

      private static  MediaElement mediaElement = new MediaElement();
        private static  SpeechSynthesizer Synthesizer = new SpeechSynthesizer();
    
        public MainPage()
        {
            this.InitializeComponent();
    
            MyRootGrid.Children.Add(mediaElement);
        }