none
Can you determine the volume that the User's default playback device is set to (using User32.dll)? RRS feed

  • Question

  • I know from other posts that I can lower and raised the volume of the User's device. But also, can I determine the volume it is set to, and can I set the volume programatically?

    Robert Homes

    Wednesday, August 30, 2017 1:31 AM

All replies

  • Hi Robert Homes,

    We could set Windows System Sound Volume programmatically. like this:

    Imports System.Runtime.InteropServices
    
    Public Class Form2
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
    
        Private Const APPCOMMAND_VOLUME_MUTE As Integer = &H80000
        Private Const APPCOMMAND_VOLUME_UP As Integer = &HA0000
        Private Const APPCOMMAND_VOLUME_DOWN As Integer = &H90000
        Private Const WM_APPCOMMAND As Integer = &H319
    
        <DllImport("user32.dll")>
        Public Shared Function SendMessageW(hWnd As IntPtr, Msg As Integer, wParam As IntPtr, lParam As IntPtr) As IntPtr
        End Function
    
        Private Sub Mute()
            SendMessageW(Me.Handle, WM_APPCOMMAND, Me.Handle, IntPtr.op_Explicit(APPCOMMAND_VOLUME_MUTE))
        End Sub
    
        Private Sub VolDown()
            SendMessageW(Me.Handle, WM_APPCOMMAND, Me.Handle, IntPtr.op_Explicit(APPCOMMAND_VOLUME_DOWN))
        End Sub
    
        Private Sub VolUp()
            SendMessageW(Me.Handle, WM_APPCOMMAND, Me.Handle, IntPtr.op_Explicit(APPCOMMAND_VOLUME_UP))
        End Sub
    End Class

    Best regards,

    Cole


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, August 30, 2017 7:51 AM
    Moderator
  • Cole,

    That doesn't answer my question. What I need to do is to determine what volume the User's system is already set to, and how to set that exact volume later. Turning the volume up or down doesn't do it. Can you help with this?


    Robert Homes

    Wednesday, August 30, 2017 1:04 PM
  •  After seeing a few of your recent questions about playing music and controlling the volume,  is there a reason you don't just use an axWindowsMediaPlayer control to play your music files?  You can easily control it's volume between 0 and 100 with a Timer.  Just set it's Visible property to False and you won`t see it at run time.  This would also stop you from effecting the volume in the users mixer.

     The below example will play a video or audio file and slowly fade the volume out after 30 seconds.  You can try it in a new Form project with 1 Button,  1 Timer,  and  1 AxWindowsMediaPlayer control added to the form.

    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            AxWindowsMediaPlayer1.Visible = False
            AxWindowsMediaPlayer1.settings.autoStart = True
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            'Play("C:\Test\Vids\cc.avi")
            Play("C:\Test\Sounds\Saturday Night Special.mp3")
        End Sub
    
        Private Sub Play(filename As String)
            Timer1.Stop()
            AxWindowsMediaPlayer1.Ctlcontrols.stop()
            AxWindowsMediaPlayer1.settings.volume = 100 'set the volume to max (100)
            AxWindowsMediaPlayer1.URL = filename
            Timer1.Interval = 30000 'aprox. 30 seconds before music starts fading out
            Timer1.Start()
            Me.Text = "Playing..."
        End Sub
    
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Timer1.Interval = 100 'you can adjust this to change fade out timing
            AxWindowsMediaPlayer1.settings.volume -= 2 'you can also adjust how much you lower the volume to change fade out speed
            If AxWindowsMediaPlayer1.settings.volume = 0 Then
                Timer1.Stop()
                AxWindowsMediaPlayer1.Ctlcontrols.stop()
                Me.Text = "Stopped..."
            Else
                Me.Text = "Fading..."
            End If
        End Sub
    End Class
    


    If you say it can`t be done then i`ll try it

    Wednesday, August 30, 2017 5:58 PM
  • I haven't used Windows Media Player because when I try to add it to my toolbar I get an error message, so abandoned that idea.

    Robert Homes

    Wednesday, August 30, 2017 6:02 PM
  • I haven't used Windows Media Player because when I try to add it to my toolbar I get an error message, so abandoned that idea.

    Robert Homes

    Hi

    Well, on my system it is as simple as Right click on ToolBox, Choose Items, select COM Tab, scroll down to Windows Media Player, select it, OK.

    It is pretty far down the list, beyond the 'MicroSoft stuff' and close to the end of the list.


    Regards Les, Livingston, Scotland

    Wednesday, August 30, 2017 6:55 PM
  • Cole,

    That doesn't answer my question. What I need to do is to determine what volume the User's system is already set to, and how to set that exact volume later. Turning the volume up or down doesn't do it. Can you help with this?


    Robert Homes

    Robert,

    Maybe, I don't know if you've recognized it. I never help with this kind of questions. At a certain moment a schoolkid finds it here and makes what he or she calls a fun app to bully others by blowing their speakers or headphones. In my opinion a programmer should not interfer with OS settings for which are normal OS features.

    Not personal meant. 

    Cor


    Success
    Cor

    Wednesday, August 30, 2017 7:00 PM
  • Hi

    If you want, here is some code that may help. This example needs the controls as shown below, and copy/replace the default Form1 code with the code below.

    This code shows how to keep the Volume level between runs, and you could fade in/out as you see fit (you will need to code that yourself though - the variables are there already)

    For the first run, you won't have a saved playlist, so, uncomment the lines between the marked lines and edit/add the PlayList.appendItem lines to suit. This will create your first PlayList and save it. Once you have done that you can comment them back out (or delete them)

    As it stands, this is  bare bones code with lots missing (such as add an item to the PlayList etc). Also, the is NO error checking included.

    Option Explicit On
    Option Strict On
    Imports WMPLib
    Public Class Form1
        Dim WithEvents AxWindowsMediaPlayer1 As New WindowsMediaPlayer
        Dim DataPath As String = Application.StartupPath & "\Data\"
        Dim PlayList As IWMPPlaylist = AxWindowsMediaPlayer1.newPlaylist("PL", Nothing)
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            '=======================================
            'PlayList.appendItem(AxWindowsMediaPlayer1.newMedia("C:\Users\lesha\Desktop\Plans\New folder\Waterloo.wav"))
            'PlayList.appendItem(AxWindowsMediaPlayer1.newMedia("C:\Users\lesha\Desktop\Plans\New folder\Waterloo.wma"))
            '  SavePlayList()
            '=======================================
    
    
            LoadPlayList()
    
            AxWindowsMediaPlayer1.currentPlaylist = PlayList
    
            For i As Integer = 0 To PlayList.count - 1
                ListBox1.Items.Add(IO.Path.GetFileName(PlayList.Item(i).sourceURL))
            Next
    
            Vol.Value = My.Settings.UserVolume
            Label5.Text = Vol.Value.ToString
    
            Bal.Value = My.Settings.UserBalance
            Label6.Text = Bal.Value.ToString
    
            Timer1.Interval = 50
            Timer1.Enabled = True
        End Sub
        Sub LoadPlayList()
            Dim Path As String = DataPath & "PlayList.txt"
            If IO.File.Exists(Path) Then
                Dim line As String = Nothing
                Using sr As IO.StreamReader = New IO.StreamReader(Path)
                    Do
                        line = sr.ReadLine()
                        If Not line = Nothing Then
                            PlayList.appendItem(AxWindowsMediaPlayer1.newMedia(line))
                        End If
                    Loop Until line = Nothing
                End Using
            End If
        End Sub
        Public Sub SavePlayList()
            Dim Path As String = DataPath & "PlayList.txt"
            Dim pp As String = My.Computer.FileSystem.GetParentPath(Path)
            If IO.Directory.Exists(pp) Then
                Using sr As IO.StreamWriter = New IO.StreamWriter(Path, False)
                    For i As Integer = 0 To PlayList.count - 1
                        sr.WriteLine(PlayList.Item(i).sourceURL)
                    Next
                End Using
            Else
                IO.Directory.CreateDirectory(pp)
                SavePlayList()
            End If
        End Sub
    
        Private Sub PlayFile(ByVal url As String)
            AxWindowsMediaPlayer1.URL = url
            '   AxWindowsMediaPlayer1.controls.play()
        End Sub
        Private Sub AxWindowsMediaPlayer1_PlayStateChange(newstate As Integer)
            Select Case newstate
                Case 0      ' Undefined
                    Label3.Text = "Undefined"
                Case 1      ' Stopped
                    Label3.Text = "Stopped"
                    Button1.Text = "Play"
                Case 2      ' Paused
                    Label3.Text = "Paused"
                    Button1.Text = "Play"
                Case 3     ' Playing
                    Label3.Text = "Playing"
                    Button1.Text = "Pause"
                Case 4      ' ScanForward
                    Label3.Text = "ScanForward"
                Case 5      ' ScanReverse
                    Label3.Text = "ScanReverse"
                Case 6     ' Buffering
                    Label3.Text = "Buffering"
                Case 7      ' Waiting
                    Label3.Text = "Waiting"
                Case 8      ' MediaEnded
                    Label3.Text = "MediaEnded"
                Case 9      ' Transitioning
                    Label3.Text = "Transitioning"
                Case 10     ' Ready
                    Label3.Text = "Ready"
                Case 11     ' Reconnecting
                    Label3.Text = "Reconnecting"
                Case 12     ' Last
                    Label3.Text = "Last"
                Case Else
                    Label3.Text = ("Unknown State: " & newstate.ToString())
            End Select
        End Sub
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            AxWindowsMediaPlayer1.controls.stop()
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Select Case Button1.Text
                Case "Play"
                    AxWindowsMediaPlayer1.controls.play()
                Case "Pause"
                    AxWindowsMediaPlayer1.controls.pause()
            End Select
        End Sub
        Private Sub Timer1_Tick_1(sender As Object, e As EventArgs) Handles Timer1.Tick
            Label1.Text = AxWindowsMediaPlayer1.controls.currentPosition.ToString("000.00")
        End Sub
        Private Sub VolumeBar_Scroll(ByVal sender As System.Object, ByVal e As EventArgs) Handles Vol.Scroll
            AxWindowsMediaPlayer1.settings.volume = Vol.Value
            My.Settings.UserVolume = AxWindowsMediaPlayer1.settings.volume
            Label5.Text = Vol.Value.ToString
        End Sub
        Private Sub BalanceBar_Scroll(ByVal sender As System.Object, ByVal e As EventArgs) Handles Bal.Scroll
            AxWindowsMediaPlayer1.settings.balance = Bal.Value
            My.Settings.UserBalance = Bal.Value
            Label6.Text = Bal.Value.ToString
        End Sub
        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            AxWindowsMediaPlayer1.settings.balance = 0
            My.Settings.UserBalance = 0
            Label6.Text = "0"
            Bal.Value = 0
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            Dim lb As ListBox = DirectCast(sender, ListBox)
            AxWindowsMediaPlayer1.controls.playItem(PlayList.Item(lb.SelectedIndex))
        End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Wednesday, August 30, 2017 8:12 PM
    Wednesday, August 30, 2017 8:08 PM
  • I haven't used Windows Media Player because when I try to add it to my toolbar I get an error message, so abandoned that idea.

    Robert Homes

     Well,  that would probably be the easiest way to do what you need without monkeying with the users volume mixer settings.  Without knowing the error you get and how you are adding it to the toolbox, it is hard to say why you get an error.

     Here is another way you can try if the AxWindowsMediaPlayer is a no go.  Use the mciSendString api function to control the audio.  The below example does the same thing as my last example but,  it uses the api function to open, play, set the volume, stop,  and close the audio file.

    Imports System.Runtime.InteropServices
    
    Public Class Form1
        <DllImport("winmm.dll", EntryPoint:="mciSendStringW")>
        Private Shared Function mciSendStringW(<MarshalAs(UnmanagedType.LPTStr)> ByVal lpszCommand As String, <MarshalAs(UnmanagedType.LPWStr)> ByVal lpszReturnString As System.Text.StringBuilder, ByVal cchReturn As UInteger, ByVal hwndCallback As IntPtr) As Integer
        End Function
    
        Private SndFilePath As String = "C:\Test\Sounds\Saturday Night Special.mp3"
        Private SndAliasName As String = "MyMediaPlayer"
        Private Volume As Integer = 0
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If mciSendStringW("open " & Chr(34) & SndFilePath & Chr(34) & " alias " & SndAliasName, Nothing, 0, IntPtr.Zero) = 0 Then
                Volume = 1000 'full volume
                mciSendStringW("setaudio " & SndAliasName & " volume to " & Volume.ToString, Nothing, 0, IntPtr.Zero)
                If mciSendStringW("play " & SndAliasName, Nothing, 0, IntPtr.Zero) = 0 Then
                    Timer1.Interval = 30000
                    Timer1.Start()
                    Button1.Enabled = False
                End If
            End If
        End Sub
    
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Timer1.Interval = 100
            Volume -= 20
            If Volume < 0 Then Volume = 0
            mciSendStringW("setaudio " & SndAliasName & " volume to " & Volume.ToString, Nothing, 0, IntPtr.Zero)
            If Volume = 0 Then
                mciSendStringW("stop " & SndAliasName, Nothing, 0, IntPtr.Zero)
                mciSendStringW("close " & SndAliasName, Nothing, 0, IntPtr.Zero)
                Button1.Enabled = True
            End If
        End Sub
    End Class
    


    If you say it can`t be done then i`ll try it

    Wednesday, August 30, 2017 9:53 PM
  • Les,

    Yes, that is what I tried to do. But when I click on the COM tab, crash!


    Robert Homes

    Wednesday, August 30, 2017 10:34 PM
  • Les,

    Yes, that is what I tried to do. But when I click on the COM tab, crash!


    Robert Homes

    Hi

    Sound like a re-install is necessary. It is no wonder you are having such a hard time with your audio application.


    Regards Les, Livingston, Scotland

    Wednesday, August 30, 2017 11:24 PM
  • Les,

    I finally got Windows Media Player into my references list, so I tried to get your suggested form working. However, I'm having trouble with the variables VOL and BAL. You don't define those in the form, and I can't tell what type of variables they are. Integer and Long don't work. Please help me with this.


    Robert Homes

    Thursday, August 31, 2017 11:44 AM
  • Les,

    I finally got Windows Media Player into my references list, so I tried to get your suggested form working. However, I'm having trouble with the variables VOL and BAL. You don't define those in the form, and I can't tell what type of variables they are. Integer and Long don't work. Please help me with this.


    Robert Homes

    Hi

    Sorry about that. Both Vol and Bal are TrackBar controls (top left of image). Each has a My.Settings variable associated with them, UserVolume and UserBalance, which store the values between runs.


    Regards Les, Livingston, Scotland

    Thursday, August 31, 2017 12:06 PM