<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web Synthesizer</title>
    <style>
        /* Stylesheet for the synthesizer */

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background-color: #333;
            color: #fff;
        }

        .synth-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        h1 {
            text-align: center;
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            margin-bottom: 20px;
        }

        .controls label {
            margin-right: 10px;
        }

        .controls input,
        .controls select {
            margin-right: 20px;
        }

        .keyboard {
            display: flex;
            position: relative;
            height: 200px;
            margin: 0 auto;
        }

        .key {
            border: 1px solid #000;
            border-radius: 5px;
        }

        .white {
            width: 60px;
            background: #fff;
            z-index: 1;
        }

        .black {
            width: 40px;
            background: #000;
            position: absolute;
            margin-left: -20px;
            height: 120px;
            z-index: 2;
        }

        .key:active {
            background: #ccc;
        }

        .key.black:active {
            background: #555;
        }

        /* Positioning keys based on notes */
        .key[data-note="C"] { left: 0px; }
        .key[data-note="C#"] { left: 45px; }
        .key[data-note="D"] { left: 60px; }
        .key[data-note="D#"] { left: 105px; }
        .key[data-note="E"] { left: 120px; }
        .key[data-note="F"] { left: 180px; }
        .key[data-note="F#"] { left: 225px; }
        .key[data-note="G"] { left: 240px; }
        .key[data-note="G#"] { left: 285px; }
        .key[data-note="A"] { left: 300px; }
        .key[data-note="A#"] { left: 345px; }
        .key[data-note="B"] { left: 360px; }

        /* Responsive design for smaller screens */
        @media (max-width: 600px) {
            .controls {
                flex-direction: column;
                align-items: center;
            }

            .keyboard {
                transform: scale(0.8);
            }
        }
    </style>
</head>
<body>
    <div class="synth-container">
        <h1>Web Synthesizer</h1>
        <button id="start-button">Start Synth</button>
        <div class="controls">
            <label for="waveform">Waveform:</label>
            <select id="waveform">
                <option value="sine">Sine</option>
                <option value="square">Square</option>
                <option value="sawtooth">Sawtooth</option>
                <option value="triangle">Triangle</option>
            </select>
            <label for="volume">Volume:</label>
            <input type="range" id="volume" min="0" max="1" step="0.01" value="0.5">
            <label for="cutoff">Filter Cutoff:</label>
            <input type="range" id="cutoff" min="100" max="10000" step="1" value="5000">
            <label for="resonance">Filter Resonance:</label>
            <input type="range" id="resonance" min="0" max="20" step="0.1" value="1">
        </div>
        <div class="keyboard">
            <!-- White Keys -->
            <div class="key white" data-note="C" tabindex="0"></div>
            <div class="key black" data-note="C#" tabindex="0"></div>
            <div class="key white" data-note="D" tabindex="0"></div>
            <div class="key black" data-note="D#" tabindex="0"></div>
            <div class="key white" data-note="E" tabindex="0"></div>
            <div class="key white" data-note="F" tabindex="0"></div>
            <div class="key black" data-note="F#" tabindex="0"></div>
            <div class="key white" data-note="G" tabindex="0"></div>
            <div class="key black" data-note="G#" tabindex="0"></div>
            <div class="key white" data-note="A" tabindex="0"></div>
            <div class="key black" data-note="A#" tabindex="0"></div>
            <div class="key white" data-note="B" tabindex="0"></div>
        </div>
    </div>
    <script>
        /* JavaScript code for the synthesizer functionality */

        let audioContext;
        let masterGain;
        let filter;
        let activeNotes = {};
        let isAudioInitialized = false;

        // Map of note frequencies
        const noteFrequencies = {
            'C': 261.63,
            'C#': 277.18,
            'D': 293.66,
            'D#': 311.13,
            'E': 329.63,
            'F': 349.23,
            'F#': 369.99,
            'G': 392.00,
            'G#': 415.30,
            'A': 440.00,
            'A#': 466.16,
            'B': 493.88
        };

        // Initialize audio context after user interaction
        document.getElementById('start-button').addEventListener('click', () => {
            try {
                // Use webkitAudioContext for Safari compatibility
                const AudioContext = window.AudioContext || window.webkitAudioContext;
                audioContext = new AudioContext();

                // Master gain node for volume control
                masterGain = audioContext.createGain();
                masterGain.gain.value = parseFloat(document.getElementById('volume').value);
                masterGain.connect(audioContext.destination);

                // Low-pass filter
                filter = audioContext.createBiquadFilter();
                filter.type = 'lowpass';
                filter.frequency.value = parseFloat(document.getElementById('cutoff').value);
                filter.Q.value = parseFloat(document.getElementById('resonance').value);
                filter.connect(masterGain);

                // Unlock audio on iOS devices with a short beep
                const osc = audioContext.createOscillator();
                osc.connect(audioContext.destination);
                osc.start();
                osc.stop(audioContext.currentTime + 0.01);

                isAudioInitialized = true;
                document.getElementById('start-button').disabled = true;
            } catch (error) {
                console.error('Error initializing audio context:', error);
            }
        });

        // Function to start a note
        function noteOn(note) {
            if (!isAudioInitialized) return;
            if (activeNotes[note]) return; // Prevent duplicate notes

            try {
                const osc = audioContext.createOscillator();
                const gainNode = audioContext.createGain();

                osc.type = document.getElementById('waveform').value;
                osc.frequency.value = noteFrequencies[note];

                // ADSR envelope (attack and release only)
                const now = audioContext.currentTime;
                gainNode.gain.setValueAtTime(0, now);
                gainNode.gain.linearRampToValueAtTime(1, now + 0.1); // Attack
                gainNode.gain.setValueAtTime(1, now + 0.1);

                osc.connect(gainNode);
                gainNode.connect(filter);
                osc.start();

                activeNotes[note] = { osc, gainNode };
            } catch (error) {
                console.error('Error starting note:', error);
            }
        }

        // Function to stop a note
        function noteOff(note) {
            if (!activeNotes[note]) return;

            try {
                const { osc, gainNode } = activeNotes[note];
                const now = audioContext.currentTime;

                // Release phase
                gainNode.gain.cancelScheduledValues(now);
                gainNode.gain.setValueAtTime(gainNode.gain.value, now);
                gainNode.gain.linearRampToValueAtTime(0, now + 0.5);

                osc.stop(now + 0.5); // Stop oscillator after release phase
                setTimeout(() => {
                    osc.disconnect();
                    gainNode.disconnect();
                }, 600);

                delete activeNotes[note];
            } catch (error) {
                console.error('Error stopping note:', error);
            }
        }

        // Event listeners for keyboard keys
        const keys = document.querySelectorAll('.key');
        keys.forEach(key => {
            const note = key.getAttribute('data-note');

            // Mouse events
            key.addEventListener('mousedown', () => {
                noteOn(note);
            });

            key.addEventListener('mouseup', () => {
                noteOff(note);
            });

            // Touch events for mobile devices
            key.addEventListener('touchstart', (e) => {
                e.preventDefault();
                noteOn(note);
            });

            key.addEventListener('touchend', (e) => {
                e.preventDefault();
                noteOff(note);
            });

            // Keyboard navigation
            key.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    noteOn(note);
                }
            });

            key.addEventListener('keyup', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    noteOff(note);
                }
            });
        });

        // Real-time control updates
        document.getElementById('waveform').addEventListener('change', () => {
            // Waveform changes will affect new notes
        });

        document.getElementById('volume').addEventListener('input', (e) => {
            if (masterGain) {
                masterGain.gain.setValueAtTime(parseFloat(e.target.value), audioContext.currentTime);
            }
        });

        document.getElementById('cutoff').addEventListener('input', (e) => {
            if (filter) {
                filter.frequency.setValueAtTime(parseFloat(e.target.value), audioContext.currentTime);
            }
        });

        document.getElementById('resonance').addEventListener('input', (e) => {
            if (filter) {
                filter.Q.setValueAtTime(parseFloat(e.target.value), audioContext.currentTime);
            }
        });
    </script>
</body>
</html>
 

HTML Online Editor & Compiler

Write, Run & Share HTML code online using OneCompiler's HTML online Code editor for free. It's one of the robust, feature-rich online Code editor for HTML language, running on the latest version HTML5. Getting started with the OneCompiler's HTML compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as HTML. You can also specify the stylesheet information in styles.css tab and scripts information in scripts.js tab and start coding.

About HTML

HTML(Hyper Text Markup language) is the standard markup language for Web pages, was created by Berners-Lee in the year 1991. Almost every web page over internet might be using HTML.

Syntax help

Fundamentals

  • Any HTML document must start with document declaration <!DOCTYPE html>
  • HTML documents begin with <html> and ends with </html>
  • Headings are defined with <h1> to <h6> where <h1> is the highest important heading and <h6> is the least important sub-heading.
  • Paragrahs are defined in <p>..</p> tag.
  • Links are defined in <a> tag.

    Example:

    <a href="https://onecompiler.com/html">HTML online compiler</a>
  • Images are defined in <img> tag, where src attribute consists of image name.
  • Buttons are defined in <button>..</button> tag
  • Lists are defined in <ul> for unordered/bullet list and <ol> for ordered/number list, and the list items are defined in <li>.

HTML Elements and Attributes

  • HTML element is everything present from start tag to end tag.
  • The text present between start and end tag is called HTML element content.
  • Anything can be a tagname but it's preferred to put the meaningful title to the content present as tag name.
  • Do not forget the end tag.
  • Elements with no content are called empty elements.
  • Elements can have attributes which provides additional information about the element.
  • In the below example, href is an attribute and a is the tag name.

    Example:

    <a href="https://onecompiler.com/html">HTML online compiler</a>

CSS

CSS(cascading style sheets) describes how HTML elements will look on the web page like color, font-style, font-size, background color etc.

Example:

Below is a sample style sheet which displays heading in green and in Candara font with padding space of 25px.

body{
  padding: 25px;
}
.title {
	color: #228B22;
	font-family: Candara;
}

HTML Tables

  • HTML Tables are defined in <table> tag.
  • Table row should be defined in <tr> tag
  • Table header should be defined in <th> tag
  • Table data should be defined in <td> tag
  • Table caption should be defined in <caption> tag

HTML-Javascript

  • Javascript is used in HTML pages to make them more interactive.
  • <script> is the tag used to write scripts in HTML
  • You can either reference a external script or write script code in this tag.

Example

<script src="script.js"></script>