Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head><title>SOUND</title></head>
<body>
<div>Frequence: <span id="frequency"></span></div>
<script type="text/javascript">
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var oscillatorNode = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
var mute = true;
var frequency = 500;
var direction = "";
var volume = 0.8;
var speed = 1;
var grossTune = 5;
var mediumTune = 0.5;
var fineTune = 0.05;
var keys = [
{key:81, direction:"down", tune:grossTune}, //q
{key:87, direction:"up", tune:grossTune}, //w
{key:69, direction:"down", tune:mediumTune},//e
{key:82, direction:"up", tune:mediumTune}, //r
{key:84, direction:"down", tune:fineTune}, //t
{key:89, direction:"up", tune:fineTune} //y
];
oscillatorNode.connect(gainNode);
gainNode.connect(audioCtx.destination)
oscillatorNode.start();
oscillatorNode.frequency.value = frequency;
gainNode.gain.value = 0;
(function manualLoop() {
setTimeout(function() {
manualLoop();
if (direction == "up"){
frequency += speed;
}
if (direction == "down"){
frequency -= speed;
}
oscillatorNode.frequency.value = frequency;
document.getElementById('frequency').innerHTML = frequency.toFixed(2);
}, 40)
}());
document.addEventListener('keydown', function(event) {
if (event.keyCode == 32) { // space bar
if (mute) {
gainNode.gain.value = volume;
mute = false;
} else {
gainNode.gain.value = 0;
mute = true;
}
}
for (var i = keys.length - 1; i >= 0; i--) {
if(event.keyCode == keys[i].key) {
direction = keys[i].direction;
speed = keys[i].tune;
}
}
});
document.addEventListener('keyup', function(event) {
direction = "";
});
</script>
</body>
</html>
@jurchiks

This comment has been minimized.

jurchiks commented Sep 28, 2017

I would add info on the keybindings at the bottom of the page contents so that you don't have to re-read the code every time you want to generate a sound:

<div>
    <ul>
        <li>Space - on/off</li>
        <li>Q - Frequency+++</li>
        <li>W - Frequency---</li>
        <li>E - Frequency++</li>
        <li>R - Frequency--</li>
        <li>T - Frequency+</li>
        <li>Y - Frequency-</li>
    </ul>
</div>

, and also rework the <span id="frequency"></span> into an <input type="number" id="frequency" min="0.00" step="0.01" /> + add listeners to it.
Which I'll probably do because this sounds like fun. Just gotta figure out how to implement corresponding visuals and add multiple sound channels, etc.

@tomMoulard

This comment has been minimized.

tomMoulard commented Oct 7, 2017

I just made a few changes to the original code for a bit more mobile user friendly and the possibility to add an optional argument in the url to set the frequency.

<!DOCTYPE html>
<html>

<head>
    <title>Sound -</title>
</head>

<body>
    <div>Frequence: <span id="frequency"></span></div>
    <button type="button" id="play" onclick="play()">Play</button>
    <button type="button" id="pause" onclick="pause()">Pause</button>
    <div>
        <table>
            <tr>
                <td>Space - on/off</td>
                <td>
                </td>
            </tr>
            <tr>
                <td>a - Frequency---</td>
                <td>
                    <button type="button" id="a" onclick="setFrequence(keys[0]);">---</button>
                </td>
            </tr>
            <tr>
                <td>z - Frequency+++</td>
                <td>
                    <button type="button" id="z" onclick="setFrequence(keys[1])">+++</button>
                </td>
            </tr>
            <tr>
                <td>e - Frequency--</td>
                <td>
                    <button type="button" id="e" onclick="setFrequence(keys[2])">--</button>
                </td>
            </tr>
            <tr>
                <td>r - Frequency++</td>
                <td>
                    <button type="button" id="r" onclick="setFrequence(keys[3])">++</button>
                </td>
            </tr>
            <tr>
                <td>t - Frequency-</td>
                <td>
                    <button type="button" id="t" onclick="setFrequence(keys[4])">-</button>
                </td>
            </tr>
            <tr>
                <td>y - Frequency+</td>
                <td>
                    <button type="button" id="y" onclick="setFrequence(keys[5])">+</button>
                </td>
            </tr>
        </table>
        <p>
            <a href="https://gist.github.com/steventhebrave/7c16a72fb940b05b5e5218390418b5bf">Source</a> : 
            <a href="https://gist.github.com/steventhebrave">Author</a>
        </p>
    </div>
    <script type="text/javascript">
    var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
    var oscillatorNode = audioCtx.createOscillator();
    var gainNode = audioCtx.createGain();
    var mute = true;
    var frequency = 500;
    var direction = "";
    var volume = 0.8;
    var speed = 1;
    var grossTune = 5;
    var mediumTune = 0.5;
    var fineTune = 0.05;
    var playButton = document.getElementById("play");
    var pauseButton = document.getElementById("pause");
    pauseButton.style.visibility = 'hidden';
    var keys = [
        // {key:81, direction:"down", tune:grossTune, val: -5}, //q
        // {key:87, direction:"up", tune:grossTune, val: 5},   //w
        // {key:69, direction:"down", tune:mediumTune, val: -1},//e
        // {key:82, direction:"up", tune:mediumTune, val: 1},  //r
        // {key:84, direction:"down", tune:fineTune, val: -0.25},  //t
        // {key:89, direction:"up", tune:fineTune, val: 0.25}     //y
        { key: 65, direction: "down", tune: grossTune, val: -5 }, //a
        { key: 90, direction: "up", tune: grossTune, val: 5 }, //z
        { key: 69, direction: "down", tune: mediumTune, val: -1 }, //e
        { key: 82, direction: "up", tune: mediumTune, val: 1 }, //r
        { key: 84, direction: "down", tune: fineTune, val: -0.25 }, //t
        { key: 89, direction: "up", tune: fineTune, val: 0.25 } //y
    ];
    var aButton = document.getElementById("a");
    var zButton = document.getElementById("z");
    var eButton = document.getElementById("e");
    var rButton = document.getElementById("r");
    var tButton = document.getElementById("t");
    var yButton = document.getElementById("y");
    function play() {
        playButton.style.visibility = 'hidden';
        pauseButton.style.visibility = 'visible';
        gainNode.gain.value = volume;
        mute = false;
    }
    function pause() {
        playButton.style.visibility = 'visible';
        pauseButton.style.visibility = 'hidden';
        gainNode.gain.value = 0;
        mute = true;
    }
    pause();
    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' +
             '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
    }
    //to use: add this a the end of the url "?freq=<num>" and <num> is a float number
    var newFreq = parseFloat(getURLParameter('freq'));
    if (newFreq){
        var frequency = newFreq;
    }
    else{
        var frequency = 500;
    }
    oscillatorNode.connect(gainNode);
    gainNode.connect(audioCtx.destination)
    oscillatorNode.start();
    oscillatorNode.frequency.value = frequency;
    gainNode.gain.value = 0;
    (function manualLoop() {
        setTimeout(function() {
            manualLoop();
            if (direction == "up") {
                frequency += speed;
            }
            if (direction == "down") {
                frequency -= speed;
            }
            oscillatorNode.frequency.value = frequency;
            document.getElementById('frequency').innerHTML = frequency.toFixed(2);
        }, 40)
    }());
    document.addEventListener('keydown', function(event) {
        if (event.keyCode == 32) { // space bar
            if (mute) {
                play();
            } else {
                pause();
            }
        }
        for (var i = keys.length - 1; i >= 0; i--) {
            if (event.keyCode == keys[i].key) {
                direction = keys[i].direction;
                speed = keys[i].tune;
            }
        }
    });

    function setFrequence(k) {
        frequency += k.val;
    }
    document.addEventListener('keyup', function(event) {
        direction = "";
    });
    </script>
</body>
</html>

(Oh and yeah, i use an azerty keyboard, sorry for being French ahah)

@GglitCch

This comment has been minimized.

GglitCch commented Dec 4, 2017

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>SOUND - by stevethebrave</title>
        <style text="text/css">
            html, body {
                overflow: hidden;
                padding: 0;
                margin: 0;
                font-family: 'Ubuntu', sans-serif;
                width: 100vh;
                height: 100vh;
                font-size: 6vh;
                background-color: #000000;
                color: #ffffff;
            }

            #text {
                position: relative;
                top: 50%;
                transform: translateY(-50%);
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="text">
            <h2>Frequence: <span id="frequency"></span></h2>
            <h2>Playing: <span id="playing">False</span></h2>
            <p>Gross Tune:  (DOWN)Q | W(UP)</p>
            <p>Medium Tune: (DOWN)E | R(UP)</p>
            <p>Fine Tune:   (DOWN)T | Y(UP)</p>
        </div>
        <script type="text/javascript">
            var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // Audio Context
            var oscillatorNode = audioCtx.createOscillator(); // Creates Oscillator Node
            var gainNode = audioCtx.createGain(); // Creates Gain Node
            var mute = true; // Muting Variable
            var frequency = 500; // Sets Frequency to 500
            var direction = ""; // Direction the User Tunes
            var volume = 0.8; // Sets Volume At Default
            var speed = 1; // Speed of Tune
            var grossTune = 5; // Q/W Tuning
            var mediumTune = 0.5; // E/R Tuning
            var fineTune = 0.05; // T/Y Tuning
            var keys = [
                { key: 81, direction: "down", tune: grossTune },        // Q Key\
                { key: 87, direction: "up", tune: grossTune },          // W Key > Fast Tuning
                { key: 65, direction: "down", tune: grossTune },        // A Key\
                { key: 90, direction: "up", tune: grossTune },          // Z Key > Fast Tuning (AZERTY Keyboards)
                { key: 69, direction: "down", tune: mediumTune },       // E Key\
                { key: 82, direction: "up", tune: mediumTune },         // R Key > Medium Tuning
                { key: 84, direction: "down", tune: fineTune },         // T Key\
                { key: 89, direction: "up", tune: fineTune }            // Y Key > Slow Tuning
            ];
            oscillatorNode.connect(gainNode); // Connects Oscillator Node to Gain Node
            gainNode.connect(audioCtx.destination) // Connects Gain Node To Browser
            oscillatorNode.start(); // Starts Node
            oscillatorNode.frequency.value = frequency;
            gainNode.gain.value = 0; // Makes Gain Value 0 at Default
            (function manualLoop() { // Declares manualLoop Function
                setTimeout(function() { // After 40 Milliseconds, do this \/
                    manualLoop(); 
                    if (direction == "up"){ // If a Key is Pressed and the Direction is Up, then
                        frequency += speed; // the Speed is added to the Frequency. 
                    }
                   if (direction == "down"){ // If a Key is Pressed and the Direction is Down, then
                        frequency -= speed; // the Speed is subtracted from the Frequency. 
                    }
                    oscillatorNode.frequency.value = frequency; // Actual Frequency to Frequency Variable. 
                    document.getElementById('frequency').innerHTML = frequency.toFixed(2); // Shows Frequency on Web Page. 
                }, 40);
            }());
            document.addEventListener('keydown', function(event) { // Key Presses
                if (event.keyCode == 32) { // Space Bar (Mute and Unmute)
                    if (mute) {            
                        gainNode.gain.value = volume;   // Sets Volume Variable to Actual Volume
                        mute = false;                   // Turns Mute to False, so if space bar is pressed again, it will be true, due to if statement
                        document.getElementById("playing").innerHTML = "True"; //                   ^
                    } else {                            //                                          |
                        gainNode.gain.value = 0;        // Sets Volume Variable to 0, Muting        |
                        mute = true;                    // What this line said: --------------------+
                        document.getElementById("playing").innerHTML = "False";
                    }
                }
                for (var i = keys.length - 1; i >= 0; i--) {
                    if(event.keyCode == keys[i].key) { // Gets Key Code and Applies to "keys" index
                        direction = keys[i].direction; // Sends Tuning in Direction of Key Pressed
                        speed = keys[i].tune; // Sets Tuning Speed
                    } 
                }
            });
            document.addEventListener('keyup', function(event) {
                direction = ""; // Sets Direction to Nothing Again
            });
        </script>
    </body>
</html>

AZERTY and QWERTY Friendly.

@nateshields

This comment has been minimized.

nateshields commented Jan 18, 2018

I added some buttons to try to get it to work for phones... the buttons seem to work okay on a desktop but not on a phone :(

`

<title>SOUND - by stevethebrave</title>
	<style text="text/css">
		button{
			height:100px;
			width:100px;
		}
        
		body {
			font-family:Verdana, Geneva, sans-serif;
			font-size:medium;
			text-align: center;
		}
      
    </style>
	
</head>
<body>
    <div id="text">
        <p/>
		<h1>Frequency: <span id="frequency"></span></h1>
        <h1>Playing: <span id="playing">False</span></h1>
		<p>	Gross </p>
        <button onmousedown = "beginAction(grossTune)" onmouseup = "endAction()" >Q</button> 
		<button onmousedown = "beginAction(-grossTune)" onmouseup = "endAction()">W</button> 
		<p>	Medium </p>
		<button onmousedown = "beginAction(mediumTune)" onmouseup = "endAction()">E</button> 
		<button onmousedown = "beginAction(-mediumTune)" onmouseup = "endAction()">R</button> 
		<p> Fine </p>
		<button onmousedown = "beginAction(fineTune)" onmouseup = "endAction()">T</button> 
		<button onmousedown = "beginAction(-fineTune)" onmouseup = "endAction()">Y</button> 
		</p>
		<button onmousedown = "togglePlayback()" >Play/Pause</button> 

    </div>
    <script type="text/javascript">
        var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // Audio Context
        var oscillatorNode = audioCtx.createOscillator(); // Creates Oscillator Node
        var gainNode = audioCtx.createGain(); // Creates Gain Node
        var mute = true; // Muting Variable
        var frequency = 300; // Sets Frequency to 500
        var direction = ""; // Direction the User Tunes
        var volume = 0.8; // Sets Volume At Default
        var speed = 1; // Speed of Tune
        var grossTune = 5; // Q/W Tuning
        var mediumTune = 0.5; // E/R Tuning
        var fineTune = 0.05; // T/Y Tuning
		var df;
        var keys = [
            { key: 81, direction: "down", tune: grossTune },        // Q Key\
            { key: 87, direction: "up", tune: grossTune },          // W Key > Fast Tuning
            { key: 65, direction: "down", tune: grossTune },        // A Key\
            { key: 90, direction: "up", tune: grossTune },          // Z Key > Fast Tuning (AZERTY Keyboards)
            { key: 69, direction: "down", tune: mediumTune },       // E Key\
            { key: 82, direction: "up", tune: mediumTune },         // R Key > Medium Tuning
            { key: 84, direction: "down", tune: fineTune },         // T Key\
            { key: 89, direction: "up", tune: fineTune }            // Y Key > Slow Tuning
        ];
        oscillatorNode.connect(gainNode); // Connects Oscillator Node to Gain Node
        gainNode.connect(audioCtx.destination) // Connects Gain Node To Browser
        oscillatorNode.start(); // Starts Node
        oscillatorNode.frequency.value = frequency;
        gainNode.gain.value = 0; // Makes Gain Value 0 at Default
        
		
		function dFreq(amount){
			frequency += amount;
		}
		function beginAction(amount){
		    df = amount;
			dFreq(amount);
			action_timeout = setInterval("dFreq(df)",100);
		}

		function endAction(){
			if (typeof(action_timeout) != "undefined") clearTimeout(action_timeout);
		}
		function togglePlayback(){
			if (mute) {            
				gainNode.gain.value = volume;   // Sets Volume Variable to Actual Volume
				mute = false;                   // Turns Mute to False, so if space bar is pressed again, it will be true, due to if statement
				document.getElementById("playing").innerHTML = "True"; //                   ^
			} else {                            //                                          |
				gainNode.gain.value = 0;        // Sets Volume Variable to 0, Muting        |
				mute = true;                    // What this line said: --------------------+
				document.getElementById("playing").innerHTML = "False";
			}
		}
		
		
		(function manualLoop() { // Declares manualLoop Function
            setTimeout(function() { // After 40 Milliseconds, do this \/
                manualLoop(); 
                if (direction == "up"){ // If a Key is Pressed and the Direction is Up, then
                    frequency += speed; // the Speed is added to the Frequency. 
                }
               if (direction == "down"){ // If a Key is Pressed and the Direction is Down, then
                    frequency -= speed; // the Speed is subtracted from the Frequency. 
                }
                oscillatorNode.frequency.value = frequency; // Actual Frequency to Frequency Variable. 
                document.getElementById('frequency').innerHTML = frequency.toFixed(2); // Shows Frequency on Web Page. 
            }, 40);
        }());
        document.addEventListener('keydown', function(event) { // Key Presses
            if (event.keyCode == 32) { // Space Bar (Mute and Unmute)
                togglePlayback();
            }
            for (var i = keys.length - 1; i >= 0; i--) {
                if(event.keyCode == keys[i].key) { // Gets Key Code and Applies to "keys" index
                    direction = keys[i].direction; // Sends Tuning in Direction of Key Pressed
                    speed = keys[i].tune; // Sets Tuning Speed
                } 
            }
			if(document.getElementById("b1").mousedown()){
				changeFreq(grossTune);
			}
        });
        document.addEventListener('keyup', function(event) {
            direction = ""; // Sets Direction to Nothing Again
        });
    </script>
</body>
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment