6

I am using System.Media.SoundPlayer to play some wav files in my project. Is it possible to change the volume of this SoundPlayer? If there is no way to do that, how can I change the volume of my computer using C#?

Beska
  • 12,421
  • 14
  • 76
  • 110
Mohamad Alhamoud
  • 4,861
  • 8
  • 30
  • 44
  • See my answer [here](https://stackoverflow.com/questions/50521363/soundplayer-adjustable-volume/50521912#50521912). – Sam May 25 '18 at 13:40

1 Answers1

3

From SoundPlayer adjustable volume:


Unfortunately SoundPlayer doesn't provide an API for changing the volume. You could use the MediaPlayer class:

using System.Windows.Media;

public class Sound
{
    private MediaPlayer m_mediaPlayer;

    public void Play(string filename)
    {
        m_mediaPlayer = new MediaPlayer();
        m_mediaPlayer.Open(new Uri(filename));
        m_mediaPlayer.Play();
    }

    // `volume` is assumed to be between 0 and 100.
    public void SetVolume(int volume)
    {
        // MediaPlayer volume is a float value between 0 and 1.
        m_mediaPlayer.Volume = volume / 100.0f;
    }
}

You'll also need to add references to the PresentationCore and WindowsBase assemblies.

LarsTech
  • 79,075
  • 14
  • 143
  • 215