?
Solved

How to play a sound while a key is pressed in my Visual Basic application?

Posted on 2016-10-24
10
Medium Priority
?
413 Views
Last Modified: 2016-10-26
Hello,

I need to play a sound when a key (let's say the Enter key) is being pressed. I can actually achieve it with either KeyDown and KeyPress events but playing a Console.Beep() for the duration of the event is what I can't do.

With Console.Beep() I need to declare both the frequency (which is linked to a TrackBar) and the duration. That's what is making me mad. I can't seem to be able to play it WHILE the key is pressed. I've tried with Int32.MaxValue for the duration but then I can't end the beep when I release the key.

Any ideas?

BTW I'm using Visual Studio 2015
0
Comment
Question by:Cesar Aracena
  • 4
  • 4
9 Comments
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 41857773
Spawn off a thread to monitor the input:

dim playSound as boolean = false 'global variable

'your thread's code.  
private sub PlaySound()
     While true
       If playSound then
         Console.Beep()
       end if
     wend
End Sub


then just (pseudo code):
keydown:
  if enterKey then
    playSound = true
   end if

keyup:
  if enterKey then
   playSound = false
 end if

Open in new window

0
 
LVL 6

Author Comment

by:Cesar Aracena
ID: 41859134
I guess my problem is more about how to change Beep()'s frequency without specifying its duration as both arguments are needed. What you propose is kinda the same I achieved with the KeyDown event and the KeyData property (where I assign a key press to look out for). The thing is that I want it to play at certain frequency and no duration set before hand.

Setting or changing the frequency is real simple with the TrackBar1.Value but the second argument (duration) is not optional in Beep() so, no matter what I do it seems I need to write some number as the second argument (in milliseconds) and no matter what else I do, it will keep playing the beep for that duration even if I add a KeyUp event which ends the beep.

This is one of the ways I achieve everything so far:
    Private Sub frmMain_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyData
            Case Keys.Enter
                Console.Beep(TrackBar1.Value, 200)
        End Select
        'End If
    End Sub

Open in new window


Any idea on how to achieve this? Maybe using other than Beep()?

Thanks!
0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 41859210
The issue with the keydown is that you're still firing events.  

So while you hold keydown . . . the buffer is getting filled with keys, which are then processed by .net

(EG: Try holding it down for less time.  Say 2 seconds).  The beeping should stop at some point.

The trick is determining a fresh key down versus a buffered key down.

Instead of keydown . . . use the keypress event to start playing, and the keyup to stop playing.
0
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

 
LVL 6

Author Comment

by:Cesar Aracena
ID: 41859397
No luck. With both KeyDown and KeyPress it will keep playing until the duration I put as the second argument reaches. And with GetAsyncKeyState with a Timer ticking, it works but while holding the key it plays a lot of small beeps instead of a long one.

I just refuse to believe that I can't make a VB app that will let me trigger a beep at a certain frequency for as long I press a button.

What I'm trying to do here is a trainer for Morse code... making a translator would be easy and even play dots and dashes as beeps as I would know how long each one is supposed to last but when a user is keying in morse code, those dots and dashes are not perfect.
0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 41859449
Would you be opposed to two different keys?  

EG:  Hit "b" for short or "n" for long (or something simliar).

Or what if you made (or found) a wav and looped it:

Dim player As New System.Media.SoundPlayer("test.wav")
player.PlayLooping()

Open in new window

0
 
LVL 6

Author Comment

by:Cesar Aracena
ID: 41859467
Thought about that... but then I'd loose the capacity to change the tone's frequency. I could make several tones and let the user select one of them but I was thinking that, using Console.Beep(), it would be better if I let the user choose the frequency using a Trackbar, which would let them find what's closer to real tones and real world conditions.
0
 
LVL 41

Accepted Solution

by:
Kyle Abrahams earned 2000 total points
ID: 41859479
Make the sound customizable then.  Let them change the wav / mp3 instead.  Or you could use something like http://www.surina.net/soundtouch/ (open source API) to change the sound dynamically.
0
 
LVL 28

Expert Comment

by:Ark
ID: 41859543
You can also have a .wav file in your resources.
To start:
My.Computer.Audio.Play(My.Resources.WaveFile, AudioPlayMode.BackgroundLoop)

Open in new window

To stop:
My.Computer.Audio.Stop()

Open in new window

0
 
LVL 6

Author Closing Comment

by:Cesar Aracena
ID: 41860499
Guess I'll surrender to VB stupidity and go with this... found a good tone generator online so I'll just make some 10 different tones and stick to those. Thanks!!!
0

Featured Post

Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Jorge
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
How can you see what you are working on when you want to see it while you to save a copy? Add a "Save As" icon to the Quick Access Toolbar, or QAT. That way, when you save a copy of a query, form, report, or other object you are modifying, you…
Watch the video to learn how one can deal with PST file corruption issue with an outstanding Kernel for Outlook PST Repair Tool easily. Using this tool, non-technical users can swiftly perform the repair process to restore their essential data witho…
Suggested Courses

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question