Skip to content

Instantly share code, notes, and snippets.

@MarkRobertJohnson
Created December 31, 2023 23:58
Show Gist options
  • Save MarkRobertJohnson/a433481db395dc3ff5e1d473ac08cc91 to your computer and use it in GitHub Desktop.
Save MarkRobertJohnson/a433481db395dc3ff5e1d473ac08cc91 to your computer and use it in GitHub Desktop.
Web Audio Synthesis Starter (two osciallators)
<html>
<!--
A Simple example using sliders to control the frequencies of two oscillators
-->
<body>
<div>
<label for="frequency1">Frequency 1: </label>
<input type="range" id="frequency1" min="0" max="4000" value="600">
<span id="frequency1Value">600</span> Hz
</div>
<div>
<label for="frequency2">Frequency 2: </label>
<input type="range" id="frequency2" min="0" max="4000" value="1040">
<span id="frequency2Value">1040</span> Hz
</div>
<button id="startAudio">Play Sound</button>
<textarea id="soundLog" rows="10" cols="50"></textarea>
<script>
// Global audio context
var audioContext;
var oscillator1, oscillator2;
var gainNode;
// Function to initialize audio components
function initializeAudio() {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
oscillator1 = audioContext.createOscillator();
oscillator2 = audioContext.createOscillator();
gainNode = audioContext.createGain();
oscillator1.connect(gainNode);
oscillator2.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator1.start();
oscillator2.start();
}
// Function to update oscillator frequency
function updateOscillatorFrequency(oscillator, frequency) {
// Log the frequency and oscillator to the the soundLog textarea
var soundLog = document.getElementById('soundLog');
soundLog.value += 'Frequency: ' + frequency + ' Hz\n';
soundLog.value += 'Oscillator: ' + oscillator + '\n\n';
// Scroll to the bottom of the textarea
soundLog.scrollTop = soundLog.scrollHeight;
oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
}
// Function to handle slider input
function handleSliderInput(sliderId, valueId, oscillator) {
var slider = document.getElementById(sliderId);
var display = document.getElementById(valueId);
slider.oninput = function() {
var frequency = this.value;
display.textContent = frequency;
updateOscillatorFrequency(oscillator, frequency);
};
}
// Start button event listener
document.getElementById('startAudio').addEventListener('click', function() {
initializeAudio();
handleSliderInput('frequency1', 'frequency1Value', oscillator1);
handleSliderInput('frequency2', 'frequency2Value', oscillator2);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment