Solved

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

Posted on 2016-10-24
10
213 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
10 Comments
 
LVL 40

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 40

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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
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 40

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 40

Accepted Solution

by:
Kyle Abrahams earned 500 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

728 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