Open In App

C# | How to play user modified Beep sound through Console

Improve
Improve
Like Article
Like
Save
Share
Report

Given a normal Console in C#, the task is to play a user modified Beep sound through the Console. User modified beep sound refers to the Beep sound played at a specific frequency for a specific duration of time.

Approach: This can be achieved with the help of Beep(Int32, Int32) method of Console Class in System package of C#.

The Beep(int, int) method of Console Class is used to play a Beep sound through the Console speaker at the specified frequency for a specified duration. These frequency and duration are specified as parameters to this method. By default, the beep plays at a frequency of 800 hertz for a duration of 200 milliseconds.

Syntax: public static void Beep (int frequency, int duration);

Parameters: This method accepts two parameters frequency and duration which are the frequency at which the Beep sound has to be played and the duration for which it is to be played, respectively.

Exceptions: This method throws following exceptions:

  • ArgumentOutOfRangeException if the frequency is less than 37 or more than 32767 hertz if the duration is less than or equal to zero.
  • HostProtectionException if this method was executed on a server, such as SQL Server, that does not permit access to a user interface.

Below programs show the use of Console.Beep(Int32, Int32) method:

Program 1:




// C# program to illustrate the use
// of Console.Beep(Int32, Int32) Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
  
namespace GFG {
  
class Program {
  
    static void Main(string[] args)
    {
  
        // Set the Frequency
        int frequency = 800;
  
        // Set the Duration
        int duration = 200;
  
        // Play beep sound once
        Console.Beep(frequency, duration);
    }
}
}


Program 2:




// C# program to illustrate the use
// of Console.Beep(Int32, Int32) Method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
  
namespace GFG {
  
class Program {
  
    // Main Method
    static void Main(string[] args)
    {
  
        int n = 5;
  
        // Set the Frequency
        int frequency = 1000;
  
        // Set the Duration
        int duration = 400;
  
        // Play beep sound n times
        for (int i = 1; i < n; i++)
            Console.Beep(frequency, duration);
    }
}
}


Note: Please run the programs on offline Visual Studio to experience the output.



Last Updated : 29 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads