# Using Generated Code from the Sound Generator Tool ## Overview The **Sound Generator Tool** outputs JavaScript code that can be used to generate sound using the Web Audio API. This code creates an oscillator, which produces periodic waveforms like sine, square, sawtooth, or triangle. The following section explains how to use the generated code such as `createOscillator('sine', 440, 0.5);` in a JavaScript environment. ## Web Audio API Basics Before using the generated code, you need to understand the key components involved: - **AudioContext**: Manages and controls the audio graph, which is the environment where audio nodes are connected. - **OscillatorNode**: Generates sound by producing waveforms at a specific frequency. - **GainNode**: Controls the volume (gain) of the audio. **Parameters Explained:** Waveform: The shape of the sound wave, which can be one of the following: 'sine': Smooth, pure tone. 'square': Harsh, buzzy sound. 'sawtooth': Brassy, bright sound. 'triangle': Similar to sine, but with a bit more harmonics. Frequency: The pitch of the sound, measured in Hertz (Hz). Higher values produce higher-pitched sounds. Volume: The gain level for the sound, where 0.0 is mute and 1.0 is the maximum volume. Further Customization You can modify the createOscillator() function to change the duration, control when the sound starts and stops, or add more advanced audio processing. ## Example: Generated Code ```javascript createOscillator('sine', 440, 0.5); This generated code instructs the browser to create a sound with: Waveform: 'sine' (can be sine, square, sawtooth, or triangle). Frequency: 440 Hz (the pitch of the sound; 440 Hz corresponds to musical note A). Volume: 0.5 (a value between 0.0 and 1.0, where 1.0 is the maximum volume). ### How to Implement This in JavaScript Since the createOscillator function is not built-in, you must define it using the Web Audio API as follows: // Function to create and play a sound function createOscillator(waveform, frequency, volume) { // Create an AudioContext instance const audioContext = new (window.AudioContext || window.webkitAudioContext)(); // Create an OscillatorNode and set its type and frequency const oscillator = audioContext.createOscillator(); oscillator.type = waveform; // e.g., 'sine', 'square', 'sawtooth', or 'triangle' oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime); // Set frequency (e.g., 440 Hz) // Create a GainNode to control volume const gainNode = audioContext.createGain(); gainNode.gain.setValueAtTime(volume, audioContext.currentTime); // Set volume (e.g., 0.5) // Connect the nodes: Oscillator -> GainNode -> Speakers oscillator.connect(gainNode); gainNode.connect(audioContext.destination); // Start the oscillator to play the sound oscillator.start(); // Stop the sound after 1 second oscillator.stop(audioContext.currentTime + 1); } // Example usage createOscillator('sine', 440, 0.5); // Plays a sine wave at 440 Hz with 50% volume