Results 1 to 9 of 9

Thread: Play a warning sound.

  1. #1

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Play a warning sound.

    Hello!

    I have a running timer progam already but I want to incorporate a warning sound. Okay, so I have a txtcustomtime where I will type the stop time of my timer. I also have a txtwarn where user can type value when the warning sound will play.

    Currently, the timer program will play a beep sound every tick of a second and plays a chime when it reaches the stop time. I want to incorporate a warning time such that when the user 5 seconds, the warning sound will play 5 seconds before the timer stops. Here is what I have now.
    Code:
       Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles BtnStart.Click
            If timerRunning Then
                ' Stop the timer
                timerRunning = False
    
                BtnReset.Enabled = True
                BtnClearOptions.Enabled = True
    
                ' Call the common method to handle button properties and other common tasks
                UpdateUIOnTimerStop()
    
                ' Enable all Radio buttons
                ''EnableAllOptionButtons()
    
                ' Stop playing the warning sound when stopping the timer
                warningSoundPlayer.Stop()
    
            Else
                ' Start the timer
                If RdoPredefinedStopTime.Checked Then
                    If CmbPredefinedTime.SelectedIndex > 0 Then
                        If RdoCountUp.Checked Then
                            ' Retrieve the selected predefined stop time
                            timerStopTime = CInt(CmbPredefinedTime.SelectedItem)
                            timerRunning = True
                            BtnStart.Text = "Stop" ' Change button text to "Stop"
                            BtnStart.BackColor = Color.Red 'Change the background color
                            BtnStart.ForeColor = Color.White ' Change the text color
                            BtnReset.Enabled = False
                            BtnClearOptions.Enabled = False
                            ' Disable all option buttons except the checked ones
                            DisableUncheckedOptionButtons()
                            Dim timerThread As New Thread(AddressOf CountUpTimer)
                            timerThread.Start()
                        ElseIf RdoCountDown.Checked Then
                            ' Retrieve the selected predefined stop time
                            timerStopTime = CInt(CmbPredefinedTime.SelectedItem)
                            timerRunning = True
                            BtnStart.Text = "Stop" ' Change button text to "Stop"
                            BtnStart.BackColor = Color.Red 'Change the background color
                            BtnStart.ForeColor = Color.White ' Change the text color
                            ' Disable the Reset and Clear Options buttons
                            BtnReset.Enabled = False
                            BtnClearOptions.Enabled = False
                            ' Disable all option buttons except the checked ones
                            DisableUncheckedOptionButtons()
                            Dim timerThread As New Thread(AddressOf CountDownTimer)
                            timerThread.Start()
    
                        Else
                            ' Retrieve the selected predefined stop time
                            timerStopTime = CInt(CmbPredefinedTime.SelectedItem)
                            timerRunning = True
                            BtnStart.Text = "Stop" ' Change button text to "Stop"
                            BtnStart.BackColor = Color.Red 'Change the background color
                            BtnStart.ForeColor = Color.White ' Change the text color
                            ' Disable the Reset and Clear Options buttons
                            BtnReset.Enabled = False
                            BtnClearOptions.Enabled = False
                            ' Disable all option buttons except the checked ones
                            DisableUncheckedOptionButtons()
                            Dim timerThread As New Thread(AddressOf RunTimer)
                            timerThread.Start()
                        End If
    
                    Else
                        MessageBox.Show("Please select a predefined stop time.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    End If
                ElseIf RdoCustomStopTime.Checked Then
                    Dim stopTimeStr As String = TxtCustomStopTime.Text
                    If RdoCountUp.Checked Then
                        If Integer.TryParse(stopTimeStr, timerStopTime) AndAlso timerStopTime >= 0 Then
                            timerRunning = True
                            BtnStart.Text = "Stop" ' Change button text to "Stop"
                            BtnStart.BackColor = Color.Red 'Change the background color
                            BtnStart.ForeColor = Color.White ' Change the text color
                            ' Disable the Reset and Clear Options buttons
                            BtnReset.Enabled = False
                            BtnClearOptions.Enabled = False
                            ' Disable all option buttons except the checked ones
                            DisableUncheckedOptionButtons()
                            Dim timerThread As New Thread(AddressOf CountUpTimer)
                            timerThread.Start()
                        Else
                            MessageBox.Show("Please enter a valid non-negative stop time in seconds.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                        End If
                    ElseIf RdoCountDown.Checked Then
                        If Integer.TryParse(stopTimeStr, timerStopTime) AndAlso timerStopTime >= 0 Then
                            timerRunning = True
                            BtnStart.Text = "Stop" ' Change button text to "Stop"
                            BtnStart.BackColor = Color.Red 'Change the background color
                            BtnStart.ForeColor = Color.White ' Change the text color
                            ' Disable the Reset and Clear Options buttons
                            BtnReset.Enabled = False
                            BtnClearOptions.Enabled = False
                            ' Disable all option buttons except the checked ones
                            DisableUncheckedOptionButtons()
                            Dim timerThread As New Thread(AddressOf CountDownTimer)
                            timerThread.Start()
                        Else
                            MessageBox.Show("Please enter a valid non-negative stop time in seconds.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                        End If
                    Else
                        'Dim stopTimeStr As String = TxtCustomStopTime.Text
                        If Integer.TryParse(stopTimeStr, timerStopTime) AndAlso timerStopTime >= 0 Then
                            timerRunning = True
                            BtnStart.Text = "Stop" ' Change button text to "Stop"
                            BtnStart.BackColor = Color.Red 'Change the background color
                            BtnStart.ForeColor = Color.White ' Change the text color
                            ' Disable the Reset and Clear Options buttons
                            BtnReset.Enabled = False
                            BtnClearOptions.Enabled = False
                            ' Disable all option buttons except the checked ones
                            DisableUncheckedOptionButtons()
                            Dim timerThread As New Thread(AddressOf RunTimer)
                            timerThread.Start()
                        Else
                            MessageBox.Show("Please enter a valid non-negative stop time in seconds.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                        End If
                    End If
                ElseIf RdoNoStopTime.Checked Then
                    ' Start timer without stop time
                    timerRunning = True
                    BtnStart.Text = "Stop" ' Change button text to "Stop"
                    BtnStart.BackColor = Color.Red 'Change the background color
                    BtnStart.ForeColor = Color.White ' Change the text color
                    ' Disable the Reset and Clear Options buttons
                    BtnReset.Enabled = False
                    BtnClearOptions.Enabled = False
                    ' Disable all option buttons except the checked ones
                    DisableUncheckedOptionButtons()
                    Dim timerThread As New Thread(AddressOf NoStopTimer)
                    timerThread.Start()
                End If
            End If
    
        End Sub
    
     Private Sub RunTimer()
            Try
                Dim startTime As DateTime = DateTime.Now
                Dim stopTime As DateTime = startTime.AddSeconds(timerStopTime)
                Dim previousSeconds As Integer = -1 ' Set to an invalid value to force tick sound play on first tick
    
                While timerRunning ' Run while the timer is running
                    Dim elapsedTime As TimeSpan = DateTime.Now - startTime
    
                    ' Play tick sound every second
                    Dim currentSeconds As Integer = CInt(elapsedTime.TotalSeconds)
                    If currentSeconds > 0 AndAlso currentSeconds <> previousSeconds Then
                        PlayTickSound()
                        previousSeconds = currentSeconds
                    End If
    
                    ' Check if elapsed time exceeds or equals the stop time
                    If elapsedTime >= TimeSpan.FromSeconds(timerStopTime) Then
                        ' Call the common method to handle button properties and other common tasks
                        UpdateUIOnTimerStop()
    
                        Exit While ' Stop timer if elapsed time equals stop time and Exit the loop after updating button properties
                    End If
    
                    ' Update timer label with elapsed time
                    UpdateTimerLabel(elapsedTime)
    
                    Thread.Sleep(100) ' Adjust sleep time for smoother execution
                End While
    
                ' Ensure the timer label displays the stop time when timer stops
                UpdateTimerLabel(TimeSpan.FromSeconds(timerStopTime))
    
                ' Play stop sound when the timer reaches the stop time
                PlayStopSound()
                timerRunning = False
    
            Catch ex As Exception
                MessageBox.Show("An error occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
    
    Private Sub CountUpTimer()
            Dim startTime As DateTime = DateTime.Now
    
            While timerRunning ' Run while the timer is running
                Dim elapsedTime As TimeSpan = DateTime.Now - startTime
    
                ' Update timer label with elapsed time
                UpdateTimerLabel(elapsedTime)
    
                ' Check if elapsed time exceeds or equals the stop time
                If elapsedTime >= TimeSpan.FromSeconds(timerStopTime) Then
                    ' Call the common method to handle button properties and other common tasks
                    UpdateUIOnTimerStop()
                    Exit While ' Stop timer if elapsed time equals stop time and Exit the loop after updating button properties
                End If
    
                Thread.Sleep(100) ' Adjust sleep time for smoother execution
            End While
    
            ' Ensure the timer label displays the stop time when timer stops
            UpdateTimerLabel(TimeSpan.FromSeconds(timerStopTime))
    
            ' Play stop sound when the timer reaches the stop time
            PlayStopSound()
            timerRunning = False
        End Sub
    
        Private Sub CountDownTimer()
            Dim stopTime As DateTime = DateTime.Now.AddSeconds(timerStopTime)
    
            While timerRunning ' Run while the timer is running
                Dim remainingTime As TimeSpan = stopTime - DateTime.Now
    
                ' Update the timer label with the remaining time
                UpdateTimerLabel(remainingTime)
    
                If remainingTime <= TimeSpan.Zero Then
                    ' Call the common method to handle button properties and other common tasks
                    UpdateUIOnTimerStop()
                    Exit While ' Exit the loop if the remaining time is negative or zero
                End If
    
                Thread.Sleep(100) ' Adjust sleep time for smoother execution
            End While
    
            ' Ensure the timer label displays the stop time when timer stops
            UpdateTimerLabel(TimeSpan.Zero)
    
            PlayStopSound() ' Play stop sound when the timer reaches the stop time
            timerRunning = False
        End Sub
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,520

    Re: Play a warning sound.

    You need an if statement, where you currently play your tick sound, you need to test if it’s 5 seconds before stop time and if so play your warning sound…

  3. #3
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    539

    Re: Play a warning sound.

    I would help, but your code is such a mess, I wouldn't know where to plug in my code for warning beeps. Also what do you mean by "I want to incorporate a warning time such that when the user 5 seconds"? Do you mean when the timer reaches 5 seconds?
    Last edited by Peter Porter; Apr 10th, 2024 at 03:34 AM.

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,520

    Re: Play a warning sound.

    Quote Originally Posted by Peter Porter View Post
    I would help, but your code is such a mess, I wouldn't know where to plug in my code for warning beeps. Also what do you mean by "I want to incorporate a warning time such that when the user 5 seconds"? Do you mean when the timer reaches 5 seconds?
    My guess is 5 seconds before stopping

  5. #5
    Fanatic Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    539

    Re: Play a warning sound.

    Code:
    Dim elapsedTime As TimeSpan = DateTime.Now - startTime
    
    ' Calculate remaining time until the timer stops
    Dim remainingTime As TimeSpan = TimeSpan.FromSeconds(timerStopTime) - elapsedTime
    
    ' Check if remaining time is equal to or less than 5 seconds
    If remainingTime <= TimeSpan.FromSeconds(5) Then
        ' Play the warning sound
        PlayWarningSound()
    End If
    Code:
    Private Sub PlayWarningSound()
        ' Create a SoundPlayer instance
        Dim player As New SoundPlayer()
    
        ' Load the system beep sound
        player.Stream = SystemSounds.Beep.Stream
    
        ' Play the beep sound repeatedly for 5 seconds
        Dim startTime As DateTime = DateTime.Now
        While DateTime.Now - startTime < TimeSpan.FromSeconds(5)
            player.PlaySync() ' Play the beep sound synchronously
            Thread.Sleep(500) ' Pause between each warning beep
        End While
    
        ' Dispose of the SoundPlayer instance to release resources
        player.Dispose()
    End Sub
    Last edited by Peter Porter; Apr 10th, 2024 at 03:44 AM.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,155

    Re: Play a warning sound.

    Just out of curiosity, why are you creating a timer rather than using one of the several Timers available to you?
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Play a warning sound.

    Quote Originally Posted by Peter Porter View Post
    I would help, but your code is such a mess, I wouldn't know where to plug in my code for warning beeps. Also what do you mean by "I want to incorporate a warning time such that when the user 5 seconds"? Do you mean when the timer reaches 5 seconds?
    I've changed my code so that it will not look messy.
    Code:
    Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles BtnStart.Click
            ' Check if any of the stop time radio buttons are checked
            If Not (RdoCustomStopTime.Checked Or RdoPredefinedStopTime.Checked Or RdoNoStopTime.Checked) Then
                MessageBox.Show("Please select one of the stop time options.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
    
            If timerRunning Then
                ' Stop the timer
                timerRunning = False
                BtnReset.Enabled = True
                BtnClearOptions.Enabled = True
    
                ' Call the common method to handle button properties and other common tasks
                UpdateUIOnTimerStop()
    
    
                If RdoCustomStopTime.Checked Or RdoPredefinedStopTime.Checked Then
                    EnableAllOptionButtons()
                    ''Clear_UncheckGrpOption2Options()
                Else
                    ' Enable GrpOption1
                    EnableStopTimeOptions()
                End If
    
            Else
                ' Start the timer
                If RdoPredefinedStopTime.Checked Then
                    If CmbPredefinedTime.SelectedIndex > 0 Then
                        timerStopTime = CInt(CmbPredefinedTime.SelectedItem)
    
                    Else
                        MessageBox.Show("Please select a predefined stop time.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                        Exit Sub
                    End If
    
                ElseIf RdoCustomStopTime.Checked Then
                    Dim stopTimeStr As String = TxtCustomStopTime.Text
                    If Not Integer.TryParse(stopTimeStr, timerStopTime) OrElse timerStopTime < 0 Then
                        MessageBox.Show("Please enter a valid non-negative stop time in seconds.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                        Exit Sub
                    End If
                End If
    
                ' Start the timer
                timerRunning = True
                BtnStart.Text = "Stop"
                BtnStart.BackColor = Color.Red
                BtnStart.ForeColor = Color.White
                BtnReset.Enabled = False
                BtnClearOptions.Enabled = False
    
                ' Disable all option buttons except the checked ones
                DisableUncheckedOptionButtons()
    
                'If RdoCustomStopTime.Checked Or RdoPredefinedStopTime.Checked Then
                '    EnableAllOptionButtons()
                'Else
                '    ' Disable Options in GrpOption2
                '    DisableOtherOptions()
                'End If
    
                ' Disable Options in GrpOption2
                ''DisableOtherOptions()
    
                ' Start the appropriate timer thread based on the selected options
                If RdoCountUp.Checked Then
                    Dim timerThread As New Thread(AddressOf CountUpTimer)
                    timerThread.Start()
                ElseIf RdoCountDown.Checked Then
                    Dim timerThread As New Thread(AddressOf CountDownTimer)
                    timerThread.Start()
                ElseIf RdoNoStopTime.Checked Then
                    Dim timerThread As New Thread(AddressOf NoStopTimer)
                    timerThread.Start()
                Else
                    Dim timerThread As New Thread(AddressOf RunTimer)
                    timerThread.Start()
                End If
            End If
        End Sub
    
     Private Sub RunTimer()
            Try
                Dim startTime As DateTime = DateTime.Now
                Dim stopTime As DateTime = startTime.AddSeconds(timerStopTime)
                Dim previousSeconds As Integer = -1 ' Set to an invalid value to force tick sound play on first tick
                'Dim warningTime As DateTime = startTime.AddSeconds(timerStopTime - TxtWarn.Text) ' Calculate warning time
    
                While timerRunning ' Run while the timer is running
                    Dim elapsedTime As TimeSpan = DateTime.Now - startTime
    
                    ' Play tick sound every second
                    Dim currentSeconds As Integer = CInt(elapsedTime.TotalSeconds)
                    If currentSeconds > 0 AndAlso currentSeconds <> previousSeconds Then
                        PlayTickSound()
                        previousSeconds = currentSeconds
                    End If
    
                    ' Check if warning is enabled and the current time equals or exceeds the warning time
                    ''If ChkWarning.Checked AndAlso DateTime.Now >= warningTime Then
                    ''    PlayWarningSound() ' Play warning sound
                    ''End If
    
                    ' Check if elapsed time exceeds or equals the stop time
                    If elapsedTime >= TimeSpan.FromSeconds(timerStopTime) Then
                        ' Call the common method to handle button properties and other common tasks
                        UpdateUIOnTimerStop()
    
                        Exit While ' Stop timer if elapsed time equals stop time and Exit the loop after updating button properties
                    End If
    
                    ' Update timer label with elapsed time
                    UpdateTimerLabel(elapsedTime)
    
                    Thread.Sleep(100) ' Adjust sleep time for smoother execution
                End While
    
                ' Ensure the timer label displays the stop time when timer stops
                UpdateTimerLabel(TimeSpan.FromSeconds(timerStopTime))
    
                ' Play stop sound when the timer reaches the stop time
                PlayStopSound()
                timerRunning = False
    
            Catch ex As Exception
                MessageBox.Show("An error occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
    
    Private Sub CountUpTimer()
            Dim startTime As DateTime = DateTime.Now
    
            While timerRunning ' Run while the timer is running
                Dim elapsedTime As TimeSpan = DateTime.Now - startTime
    
                ' Update timer label with elapsed time
                UpdateTimerLabel(elapsedTime)
    
                ' Check if elapsed time exceeds or equals the stop time
                If elapsedTime >= TimeSpan.FromSeconds(timerStopTime) Then
                    ' Call the common method to handle button properties and other common tasks
                    UpdateUIOnTimerStop()
                    Exit While ' Stop timer if elapsed time equals stop time and Exit the loop after updating button properties
                End If
    
                Thread.Sleep(100) ' Adjust sleep time for smoother execution
            End While
    
            ' Ensure the timer label displays the stop time when timer stops
            UpdateTimerLabel(TimeSpan.FromSeconds(timerStopTime))
    
            ' Play stop sound when the timer reaches the stop time
            PlayStopSound()
            timerRunning = False
        End Sub
    
        Private Sub CountDownTimer()
            Dim stopTime As DateTime = DateTime.Now.AddSeconds(timerStopTime)
    
            While timerRunning ' Run while the timer is running
                Dim remainingTime As TimeSpan = stopTime - DateTime.Now
    
                ' Update the timer label with the remaining time
                UpdateTimerLabel(remainingTime)
    
                If remainingTime <= TimeSpan.Zero Then
                    ' Call the common method to handle button properties and other common tasks
                    UpdateUIOnTimerStop()
                    Exit While ' Exit the loop if the remaining time is negative or zero
                End If
    
                Thread.Sleep(100) ' Adjust sleep time for smoother execution
            End While
    
            ' Ensure the timer label displays the stop time when timer stops
            UpdateTimerLabel(TimeSpan.Zero)
    
            PlayStopSound() ' Play stop sound when the timer reaches the stop time
            timerRunning = False
        End Sub
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,155

    Re: Play a warning sound.

    It's even less clear why you aren't just using a timer. You have three of them built into the language that do what you are doing, and do so with far less code. The Sleep(100) is a good thing, as sleeping a background thread is a good way to wait without cost, but that's what timers do anyways, and you have the same imprecision issues that a timer would have.
    My usual boring signature: Nothing

  9. #9

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Play a warning sound.

    That's I've started so I just continue doing it and besides, I am already almost finish with my code (90/100).
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width