Skip to content

Instantly share code, notes, and snippets.

@altbodhi
Created October 25, 2023 09:17
Show Gist options
  • Save altbodhi/6df21558759a831db8549e7152b1163a to your computer and use it in GitHub Desktop.
Save altbodhi/6df21558759a831db8549e7152b1163a to your computer and use it in GitHub Desktop.
Fail on Sound generating in browser
<MudButton ButtonType="ButtonType.Button" OnClick="BeepIfIncomingMessage">OK</MudButton>
@code {
async Task BeepIfIncomingMessage()
{
if (jsSoundUtils == null)
jsSoundUtils = await JS.InvokeAsync<IJSObjectReference>("import", "./js/SoundUtils.js");
var res = await jsSoundUtils.InvokeAsync<object>("soundBeep");
}
/*
Microsoft.JSInterop.JSException: Could not find 'soundBeep' ('soundBeep' was undefined).
Error: Could not find 'soundBeep' ('soundBeep' was undefined).
*/
}
// The browser will limit the number of concurrent audio contexts
// So be sure to re-use them whenever you can
const myAudioContext = new AudioContext();
/**
* Helper function to emit a beep sound in the browser using the Web Audio API.
*
* @param {number} duration - The duration of the beep sound in milliseconds.
* @param {number} frequency - The frequency of the beep sound.
* @param {number} volume - The volume of the beep sound.
*
* @returns {Promise} - A promise that resolves when the beep sound is finished.
*/
export function beep(duration, frequency, volume) {
return new Promise((resolve, reject) => {
// Set default duration if not provided
duration = duration || 200;
frequency = frequency || 440;
volume = volume || 100;
try {
let oscillatorNode = myAudioContext.createOscillator();
let gainNode = myAudioContext.createGain();
oscillatorNode.connect(gainNode);
// Set the oscillator frequency in hertz
oscillatorNode.frequency.value = frequency;
// Set the type of oscillator
oscillatorNode.type = "square";
gainNode.connect(myAudioContext.destination);
// Set the gain to the volume
gainNode.gain.value = volume * 0.01;
// Start audio with the desired duration
oscillatorNode.start(myAudioContext.currentTime);
oscillatorNode.stop(myAudioContext.currentTime + duration * 0.001);
// Resolve the promise when the sound is finished
oscillatorNode.onended = () => {
resolve();
};
} catch (error) {
reject(error);
}
});
};
window.soundBeep = beep();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment