You can create a beep sound in JavaScript using the Audio
object. Here’s an example of how to do this:
function beep() {
const audio = new Audio('beep.mp3');
audio.play();
}
In this example, a new Audio
object is created with a path to an audio file, in this case a file named beep.mp3
. The play
method is then called on the Audio
object to play the sound.
You can also use the AudioContext
API to generate audio programmatically, but it is more complex than using the Audio
object. Here’s an example of how to use the AudioContext
API to create a beep sound:
function beep() {
const context = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = 440;
oscillator.connect(context.destination);
oscillator.start();
oscillator.stop(context.currentTime + 0.5);
}
In this example, a new AudioContext
object is created, and a OscillatorNode
is created using the createOscillator
method. The type
property is set to 'sine'
to generate a sine wave, and the frequency is set to 440
Hz. The oscillator is then connected to the audio destination and started. The stop
method is called after 0.5 seconds to stop the sound.
+ There are no comments
Add yours