6

I have a class Sounds.cs that manages playing sounds in my form, and I want to be able to adjust the volume to decimal value. Is there a way to change the volume of a sound being played with a SoundPlayer object? Or is there perhaps a different way to play sound that makes this possible?

Latika Agarwal
  • 979
  • 1
  • 6
  • 11
Nolan B.
  • 110
  • 1
  • 1
  • 7
  • What do you mean by "adjust the volume to decimal value" ? Please add the code you tried. – AsthaUndefined May 25 '18 at 04:25
  • @AsthaSrivastava I haven't tried any code because I don't know where to start. I have a variable `volume` that is somewhere between 0 and 100, and I want to be able to adjust the volume of the sound played with `player.Play()`. – Nolan B. May 25 '18 at 04:27

1 Answers1

7

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.

Sam
  • 3,060
  • 1
  • 16
  • 22
  • Just what I'm looking for! How would I get the Uri of a .wav file if its an embedded resource? Would it be best to not embed them, and just use a file path? – Nolan B. May 25 '18 at 15:07
  • Ah yeah , `MediaPlayer` doesn't support that. You'll have to just put the .wav file somewhere on disk. – Sam May 27 '18 at 06:57
  • MediaPlayer appeared to work, but came with the side effect of making my windows form half its size for some odd reason. – Nolan B. May 27 '18 at 06:59
  • Woah that is super weird! Are you using WinForms? `PresentationCore` is part of WPF; maybe there is some incompatibility. – Sam May 27 '18 at 10:06
  • I had trouble finding `System.Windows.Media`. Search for `PresentationCore` in the "Add Reference..." Window of Visual Studio. You will also need the reference `WindowBase` for the `Open()` and `Play()` functions of MediaPlayer class. – Andrew Jul 15 '21 at 17:59