Subscribe

RSS Feed (xml)

Playing Simple Beep

To play a simple sound, such as the system-defined beep.

The .NET Framework does not include any managed classes for playing audio files or even for playing the system beep sound. However, you can easily bridge this gap using the Win32 API or Visual Basic .NET, which provides a legacy Beep function that's exposed through the Microsoft.VisualBasic.Interaction class. In the latter case, you must add a reference to the Microsoft.VisualBasic.dll assembly (which is included with all versions of the .NET Framework).

The following example uses both the Beep API function and the Visual Basic Beep function. Notice that the API function actually uses the computer's internal speaker and plays a tone with the indicated frequency (in hertz, ranging from 37 to 32,767) and duration (in milliseconds). This won't produce any sound if the computer does not have an internal speaker. The Visual Basic Beep function, on the other hand, plays the standard system-defined beep sound event (which is a WAV audio file). This won't produce any sound if the computer doesn't have a sound card, if the sound card is not connected to external speakers, or if Windows is configured (via the Sounds and Audio Devices section of the Control Panel) to not play sounds.

using System;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;

public class BeepTest {

    [DllImport("kernel32.dll")]
    private static extern bool Beep(int freq, int dur);

    [STAThread]
    private static void Main(string[] args) {
    
        // Play a 440 Hz tone for 100 milliseconds on the internal speaker.
        Console.WriteLine("Win32 API beep test.");
        Beep(440, 100);
        Console.ReadLine();

        // Play the default beep system sound (a WAV audio file).
        Console.WriteLine("VB beep test.");
        Interaction.Beep();
        Console.ReadLine();
    }
}

You can also use Win32 API functions to play an audio file of your choosing. This technique is described in next post.

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail