Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SoundPlayer adjustable volume

Tags:

c#

.net

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?

like image 447
Nolan B. Avatar asked May 25 '18 04:05

Nolan B.


1 Answers

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.

like image 101
Sam Avatar answered Oct 22 '22 12:10

Sam