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
Solved

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

Posted on 2016-10-24
10
113 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
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.Net - Project Software to help the Developer 7 40
VB.NET (2008) - Refactoring Question 2 23
Help with exporting to excel 4 35
Vb.net threads keep increasing 2 35
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

791 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