Recipe 10.4. Making Your Computer Beep


Problem

You want to play a simple sound or sequence of tones based on frequency and duration using the built-in speaker on your computer, rather than relying on the sound board or creating audio files specifically tailored for the purpose.

Solution

Sample code folder: Chapter 10\PlayTones

Visual Basic 2005 now provides a Console.Beep() method that plays a tone given frequency and duration parameters.

Discussion

You can use this command to create notification sounds from console applications, but you can also call this method from any Windows application to create specialized effects.

The following PlayTones() subroutine plays a sequence of tones passed to it in the form of a Point array. This data structure is ideal for the notes because each note is comprised of integer frequency and duration parameters (similar to the X and Y values of each point):

 Public Sub PlayTones(ByVal toneArray( ) As Point)    ' ----- Play a set of tones, one after another.    Dim frequency As Integer    Dim duration As Integer    For Each tone As Point In toneArray       frequency = tone.X       duration = tone.Y       Console.Beep(frequency, duration)    Next tone End Sub 

The following code creates a Point array to play a simple melody:

 Dim soundsAlien As Point( ) = { _    New Point(932, 500), _    New Point(1047, 500), _    New Point(831, 500), _    New Point(415, 500), _    New Point(622, 900)} PlayTones(soundsAlien) 

This may remind you of something each time you play it; something to do with mashed potatoes, perhaps…




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net