ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT


The single web page application featured in this tutorial web page substantiates a virtual simulation of physical keyboard (i.e. piano) musical instrument (sans the black keys and most of the white keys which would otherwise imbue the instrument with more octave range). Users of the application can press one or multiple keys of a physical computer keyboard (which displays letters and symbols such as ‘a’, ‘;’, and ‘/’) in order to play corresponding sound frequencies. Each time a particular virtual keyboard key is pressed, a time-stamped message is appended to the text in the console DIV element of the application’s web page user interface.

Note that, as of 26_JANUARY_2025 at 1:00PM Pacific Standard Time, the application which is featured on this web page has been updated slightly in order to be accessible via touchscreen interfaces. Specifically, two new event listener functions have been added to that application’s constituent JavaScript file which are the touchscreen equivalent of physical keyboard ‘keyup’ and ‘keydown’ event listener functions. (A video (in MP4 file format) demonstrating that newly-added mobile functionality is available at the Uniform Resource Locator in the paragraph after the next paragraph).

Note also that the application which is featured on this web page is being hosted on karbytes’ own dark web server (as of 1:00PM Pacific Standard Time on 26_JANUARY_2025) and is usable via the Tor mobile and desktop browser (but, if using the mobile Tor browser, video and audio playing needs to be enabled in the browser settings). That application can be used to play one or more of the twenty-two sound wave frequencies (i.e. musical notes) which are represented by graphical user interface depictions of physical keyboard instrument keys simultaneously and/or in chronological succession (where each note has a duration of approximately half of a second) via the application which is being hosted on the aforementioned server at the following Uniform Resource Locator (as of 1:00PM Pacific Standard Time on 26_JANUARY_2025): http://qkbrwfubnh4knc6kkhx6uepccavpwezdf2al7w2quepe3qociegsi3yd.onion/KARBYTES_BLOG_APPS/ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT/abridged_keyboard_musical_instrument.html

A video which serves as empirical evidence supporting the claim that the aforementioned .onion web page application is fully functional on the Tor browser application for Android operating system mobile devices is available at the following Uniform Resource Locator and features karbytes manipulating that application’s user interface keyboard keys (inside of one Tor browser tab) on its (Android) Galaxy A03s mobile device: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_28/main/abridged_keyboard_musical_instrument_(updated)_android_use_case_by_karbytes_26january2025.mp4

To view hidden text inside each of the preformatted text boxes below, scroll horizontally.


SOFTWARE_APPLICATION_COMPONENTS


Hyper-Text-Markup-Language_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/abridged_keyboard_musical_instrument.html

Cascading-Style-Sheet_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/karbytes_aesthetic.css

JavaScript_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_28/main/abridged_keyboard_musical_instrument.js


Hyper-Text-Markup-Language Code


The following Hyper-Text-Markup-Language (HTML) code defines the user interface component of the ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT web page application. Copy the HTML code from the source code file which is linked below into a text editor and save that file as abridged_keyboard_musical_instrument.html. Use a web browser such as Firefox to open that HTML file (and ensure that the JavaScript and Cascading-Style-Sheet files are in the same file directory as the HTML file).

(Note that angle brackets which resemble HTML tags (i.e. an “is less than” symbol (i.e. ‘<‘) followed by an “is greater than” symbol (i.e. ‘>’)) displayed on this web page have been replaced (at the source code level of this web page) with the Unicode symbols U+003C (which is rendered by the web browser as ‘<‘) and U+003E (which is rendered by the web browser as ‘>’). That is because the WordPress web page editor or web browser interprets a plain-text version of an “is less than” symbol followed by an “is greater than” symbol as being an opening HTML tag (which means that the WordPress web page editor or web browser deletes or fails to display those (plain-text) inequality symbols and the content between those (plain-text) inequality symbols)).

If copy-pasting the following HTML code from the preformatted text box below into a text editor, remove the zero-width space Unicode character (&​#8203;) which is located between the ‘s’ and the ‘r’ in the script tag(s) which each link to a JavaScript file.

Hyper-Text-Markup-Language_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/abridged_keyboard_musical_instrument.html

image_link: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/abridged_keyboard_musical_instrument_html_screenshot.jpeg


<!--
/**
 * file: abridged_keyboard_musical_instrument.html
 * type: Hyper-Text-Markup-Language
 * author: karbytes
 * date: 13_SEPTEMBER_2024
 * license: PUBLIC_DOMAIN
 */
 -->
<!-- 
/**
 * Note that this application contains the word "ABRIDGED" in its title
 * because the keyboard musical instrument which this application
 * simulates is missing black keys (i.e. piano keys which correspond 
 * with minor notes (as opposed to white keys which correspond with
 * major notes)) and the full range of notes which "real" pianos
 * typically include.
 */
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT</title>
    <!-- 
    /**
     * The linked Cascading-Style-Sheet file named karbytes_aesthetic.css 
     * defines how this web page (which is named abridged_keyboard_musical_instrument.html) 
     * appears when this web page is (re)loaded by the web browser. 
     */
   -->
   <link rel="stylesheet" href="karbytes_aesthetic.css">
   <style>
      /** 
       * Make the padding on the left and right side of each piece of text on this web page 
       * equal in horizontal length within that piece of text's encompassing container element.
       * 
       * Make each container element on this web page have fifty pixels of padding on the top,
       * bottom, left, and right side of that element.
       */
      body {
          text-align: center;
          padding: 50px;
      }
      /**
       * Make more padding on the left side than on the right side of the text inside of the 
       * DIV element whose class is "console" and give that DIV element a two-pixel border 
       * which is colored green and which has slightly rounded corners.
       * 
       * Pad the top of that DIV element with five pixels of margin space.
       * 
       * Pad the text inside of that DIV element with ten pixels of space between the 
       * text and the borders of that DIV element.
       */
      .console {
          text-align: left;
          border-color: #00ff00;
          border-style: solid;
          border-radius: 5px;
          border-width: 2px;
          margin-top: 5px;
          padding: 10px;
      }
      /**
       * Make the keyboard background dark gray with a two-pixel-thick GREEN border.
       * 
       * Make the keyboard have slightly rounded corners.
       */
      .keyboard {
          background-color: #606060;
          border-color: #00ff00;
          border-style: solid;
          border-radius: 5px;
          border-width: 2px;
          display: inline-block;
          padding: 10px;
      }
      /**
       * Make each keyboard key background light gray with a two-pixel-thick orange border.
       * 
       * Make the keyboard have slightly rounded corners.
       * 
       * Make the width of each keyboard key fifty pixels.
       * 
       * Make the height of each keyboard key two hundred pixels.
       * 
       * Create a gap of five pixels between adjacent keyboard keys.
       * 
       * Cause each adjacent keyboard key to be arranged horizontally rather than vertically
       * (within the confines of the encompassing HTML container element 
       * (which has a fixed width of 800 pixels)).
       * 
       * Make the text color of each keyboard key BLACK.
       */
      .key {
          background-color: #b0b0b0;
          border: 2px solid #ff9000;
          border-radius: 5px;
          width: 50px;
          height: 200px;
          margin: 5px;
          display: inline-block;
          color: #000000;
      }
      /** 
       * Cause each keyboard key's background color to turn GREEN when it is pressed
       * (i.e. when the key displayed on the web page's corresponding physical computer
       * keyboard key (e.g. 'A') is pressed by the application user).
       */
      .key.pressed {
          background-color: #00ff00;
      }
  </style>
</head>
<body onload="initialize_application()">
    <h1>ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT</h1>
    <p>Press keys on your computer's physical keyboard to play corresponding musical notes.</p>
    <div class="keyboard" id="keyboard">
        <!-- Keys will be dynamically added here. -->
    </div>
    <!-- CONSOLE (for recording event time stamps) -->
    <div class="console" id="console">???</div>
    <!-- 
    /**
     * The linked JavaScript file named abridged_keyboard_musical_instrument.js 
     * defines how this web page (which is named abridged_keyboard_musical_instrument.html) 
     * behaves when the user clicks on the menus and start and stop buttons 
     * (and when this web page is (re)loaded by the web browser). 
     */
    -->
    <script s​rc="abridged_keyboard_musical_instrument.js"></script>
</body>
</html>


Cascading-Style-Sheet Code


The following Cascading-Style-Sheet (CSS) code defines a stylesheet which customizes the appearance of interface components of the ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT web page application. Copy the CSS code from the source code file which is linked below into a text editor and save that file as karbytes_aesthetic.css.

Cascading-Style-Sheet_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/karbytes_aesthetic.css


/**
 * file: karbytes_aesthetic.css
 * type: Cascading-Style-Sheet
 * date: 10_JULY_2023
 * author: karbytes
 * license: PUBLIC_DOMAIN
 */

/** Make the page background BLACK, the text orange and monospace, and the page content width 800 pixels or less. */
body {
 	background: #000000;
 	color: #ff9000;
 	font-family: monospace;
 	font-size: 16px;
 	padding: 10px;
 	width: 800px;
}

/** Make input elements and select elements have an orange rounded border, a BLACK background, and orange monospace text. */
input, select {
	background: #000000;
	color: #ff9000;
	border-color: #ff9000;
	border-width: 1px;
	border-style: solid;
	border-radius: 5px;
	padding: 10px;
	appearance: none;  
 	font-family: monospace;
 	font-size: 16px;
}

/** Invert the text color and background color of INPUT and SELECT elements when the cursor (i.e. mouse) hovers over them. */
input:hover, select:hover {
	background: #ff9000;
	color: #000000;
}

/** Make table data borders one pixel thick and CYAN. Give table data content 10 pixels in padding on all four sides. */
td {
	color: #00ffff;
	border-color: #00ffff;
	border-width: 1px;
	border-style: solid;
	padding: 10px;
}

/** Set the text color of elements whose identifier (id) is "output" to CYAN. */
#output {
	color: #00ffff;
}

/** Set the text color of elements whose class is "console" to GREEN and make the text background of those elements BLACK. */
.console {
	color: #00ff00;
	background: #000000;
}

JavaScript Code


The following JavaScript (JS) code defines the functions which control the behavior of the ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT web page application. Copy the JS code from the source code file which is linked below into a text editor and save that file as abridged_keyboard_musical_instrument.js.

The text in the preformatted text box below appears on this web page (while rendered correctly by the web browser) to be identical to the content of the JavaScript source code file whose Uniform Resource Locator is displayed in the green hyperlink below.

JavaScript_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_28/main/abridged_keyboard_musical_instrument.js


/**
 * file: abridged_keyboard_musical_instrument.js
 * type: JavaScript
 * author: karbytes
 * date: 26_JANUARY_2025
 * license: PUBLIC_DOMAIN
 */

// Declare an audio context variable (which is a global program variable).
let audioContext = new (window.AudioContext || window.webkitAudioContext)();

/**
 * Define a global variable which is an (immutable) dictionary populated by key-value pairs (i.e. definitions)
 * where each key is the literal label of a computer keyboard key and where each value is the respective key's uniquely 
 * corresponding sound wave frequency requency (in terms of sound wave oscillations per second 
 * (i.e. hertz (abbreviated as Hz))). 
 * 
 * Each key-value pair in that dictionary is listed in ascending order in terms of sound wave frequency.
 * 
 * The musical note associated with each of those sound wave frequencies is denoted by that sound wave 
 * frequency's uniquely corresponding musical note comment.
 */
const noteFrequencies = {
    'z': 130.81,  // C3
    'x': 146.83,  // D3
    'c': 164.81,  // E3
    'v': 174.61,  // F3
    'b': 196.00,  // G3
    'n': 220.00,  // A3
    'm': 246.94,  // B3
    ',': 261.63,  // C4 (Middle C)
    '.': 293.66,  // D4
    '/': 329.63,  // E4
    'a': 349.23,  // F4
    's': 392.00,  // G4
    'd': 440.00,  // A4
    'f': 493.88,  // B4
    'g': 523.25,  // C5
    'h': 587.33,  // D5
    'j': 659.25,  // E5
    'k': 698.46,  // F5
    'l': 783.99,  // G5
    ';': 880.00,  // A5
    'q': 987.77,  // B5
    'w': 1046.50, // C6
};

// Define a global variable which represents the HTML element whose identifier (id) is "keyboard" on the web page named  abridged_keyboard_musical_instrument.
const keyboardDiv = document.getElementById('keyboard');

/**
 * Return a String type value which describes the number of milliseconds which have elapsed since the Unix Epoch.
 * 
 * Note that the Unix Epoch is 01_JANUARY_1970 at 0 hours, 0 minutes, 0 seconds, and 0 seconds 
 * (i.e. 00:00:00) (i.e. midnight) (Coordinated Universal Time (UTC)).
 * 
 * @return {String} text which denotes the number of milliseconds which have elapsed since the Unix Epoch.
 */
function generate_time_stamp() {
    const milliseconds_elapsed_since_unix_epoch = Date.now();
    return milliseconds_elapsed_since_unix_epoch + " milliseconds since midnight on 01_JANUARY_1970.";
}

/**
 * Return a String type value which is used to instantiate a paragraph type web page element such that
 * the String type value which is passed into this function as its only input is that paragraph element's 
 * inner HTML content.
 * 
 * Note that the String type constant variable values are broken up into single-character String type values 
 * to avoid causing the WordPress web page editor to interpret HTML tags in the web page body with 
 * source code which is hosted on that web page inside of PRE (preformatted) web page elements.
 * 
 * @param {String} inner_HTML is assumed to be plain text or HTML content.
 * 
 * @return {String} a sequence of text characters which is used to instantiate a paragraph (P) web page element.
 */
function generate_paragraph_html_element(inner_html) {
    const opening_paragraph_tag = ('<' + 'p' + '>'), closing_paragraph_tag = ('<' + '/' + 'p' + '>');
    try {
        if (typeof inner_html.length !== "number") throw 'The expression (typeof inner_html.length !== "number") was evaluated to be true.';
        return opening_paragraph_tag + inner_html + closing_paragraph_tag;
    }
    catch(exception) {
        console.log("An exception to normal functioning occurred during the runtime of generate_paragraph_html_element(inner_html): " + exception);
    }
}

/**
 * Respond to the event of the web page named abridged_keyboard_musical_instrument.html being loaded by a web browser.
 * 
 * This function prints a time-stamped message indicating when the web page was last 
 * loaded by the web browser in a DIV element on that web page whose identifier is "console".
 * 
 * This function also initializes the audio context (which works offline and which utilizes the
 * web browser's built-in sound-generating capabilities which correspond with the local machine's
 * operating system (to control the hardware which causes sound waves to be emitted from the machine)).
 * 
 * Assume that all three files which constitute this single web page application are located
 * in the same local file directory (and those file are 
 * karbytes_aesthetic.css, 
 * abridged_keyboard_musical_instrument.js, and 
 * abridged_keyboard_musical_instrument.html).
 */
function initialize_application() {
    // Initialize variables which are local to this function.
    let time_stamped_message = "";

    // Execute a try-catch block. If runtime exceptions are found, exit the try block and print an error message to the web browser console.
    try {
        // If the audio context has not already been defined, then define it now.
        if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();

        // Populate the div whose identifier is "console" with a time stamped message indicating that this function was called (and when it was called).
        time_stamped_message = ("The function named initialize_application() was called at time: " + generate_time_stamp());
        console.log(time_stamped_message);
        time_stamped_message = generate_paragraph_html_element(time_stamped_message);
        console_div = document.getElementById("console");
        console_div.innerHTML = time_stamped_message;
    }
    catch(exception) {
        console.log("An exception to normal functioning occurred during the runtime of initialize_application(): " + exception);
    }
}

/** 
 * This function to dynamically instantiates each piano key in the piano user interface (UI) on the corresponding web page
 * (i.e. abridged_keyboard_musical_instrument.html).
 * 
 * Specifically, this function populates the HTML element whose identifier (id) is "keyboard" with the following labeled keyboard keys
 * (where each key represents a uniquely corresponding sound wave frequency (in terms of sound wave oscillations per second 
 * (i.e. hertz (abbreviated as Hz))) and the musical note name of each of that particular frequency):
 *     'z' // 130.81 Hz (C3)
 *     'x' // 146.83 Hz (D3)
 *     'c' // 164.81 Hz (E3)
 *     'v' // 174.61 Hz (F3)
 *     'b' // 196.00 Hz (G3)
 *     'n' // 220.00 Hz (A3)
 *     'm' // 246.94 Hz (B3)
 *     ',' // 261.63 Hz (C4 (Middle C))
 *     '.' // 293.66 Hz (D4)
 *     '/' // 329.63 Hz (E4)
 *     'a' // 349.23 Hz (F4)
 *     's' // 392.00 Hz (G4)
 *     'd' // 440.00 Hz (A4)
 *     'f' // 493.88 Hz (B4)
 *     'g' // 523.25 Hz (C5)
 *     'h' // 587.33 Hz (D5)
 *     'j' // 659.25 Hz (E5)
 *     'k' // 698.46 Hz (F5)
 *     'l' // 783.99 Hz (G5)
 *     ';' // 880.00 Hz (A5)
 *     'q' // 987.77 Hz (B5)
 *     'w' // 1046.50 Hz (C6)
 */
function createKeyUI(key) {
    try {
        const keyDiv = document.createElement('div');
        keyDiv.classList.add('key');
        keyDiv.textContent = key.toUpperCase();
        keyDiv.id = key;
        keyboardDiv.appendChild(keyDiv);
    }
    catch(exception) {
        console.log("An exception to normal functioning occurred during the runtime of createKeyUI(key): " + exception);
    }
}

/**
 * This function adds keys to the keyboard DIV in ascending note order.
 */
Object.keys(noteFrequencies).forEach(createKeyUI);

/**
 * This function generates physical sound waves whose frequencies are the values input by this function.
 * 
 * This function also prints a time-stamped message indicating when a UI keyboard key was
 * most recently pressed in the "console" DIV.
 */
function playNote(frequency) {
    let time_stamped_message = "";
    try {
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        oscillator.type = 'sine';
        oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
        gainNode.gain.setValueAtTime(0.5, audioContext.currentTime);
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        oscillator.start();
        oscillator.stop(audioContext.currentTime + 0.5); // Stop playing the note after 0.5 seconds elapses. 

        // Append the text in the div whose identifier is "console" with a time stamped message indicating that this function was called (and when it was called).
        time_stamped_message = ("The function named playNote(frequency) (where frequency = " + frequency + ") was called at time: " + generate_time_stamp());
        console.log(time_stamped_message);
        time_stamped_message = generate_paragraph_html_element(time_stamped_message);
        console_div = document.getElementById("console");
        console_div.innerHTML += time_stamped_message;
    }
    catch(exception) {
        console.log("An exception to normal functioning occurred during the runtime of playNote(frequency): " + exception);
    }
}

/**
 * This function responds to the event of a UI keyboard key being pressed 
 * (as a consequence of the corresponding physical keyboard key being pressed down).
 */
document.addEventListener('keydown', (event) => {
    const key = event.key.toLowerCase();
    if (noteFrequencies[key]) {
        playNote(noteFrequencies[key]);
        // Add visual feedback to the key (by changing the background color of the corresponding key).
        const keyDiv = document.getElementById(key); 
        if (keyDiv) {
          keyDiv.classList.add('pressed');
        }
    }
});

/**
 * This function responds to the event of a UI keyboard key being unpressed
 * (as a consequence of the corresponding physical keyboard key being unpressed after being pressed).
 * 
 * Specifically, this function changes the background color of the respective key back to light gray 
 * (after temporarily being set to green (for 0.5 seconds)).
 */
document.addEventListener('keyup', (event) => {
    const key = event.key.toLowerCase();
    const keyDiv = document.getElementById(key);
    if (keyDiv) {
      keyDiv.classList.remove('pressed');
    }
});

/** 
 * This function responds to the event of a UI keyboard key being touched 
 * (and is logically equivalent to the physical key 'keydown' event listener function). 
 */
document.addEventListener('touchstart', (event) => {
    // Get the touched web page element.
    const target = event.target;

    // Check if the touched element is a key (with the 'key' class).
    if (target.classList.contains('key')) {
        const key = target.id.toLowerCase(); // Use the key's ID as the identifier.
        if (noteFrequencies[key]) {
            playNote(noteFrequencies[key]);
            // Add visual feedback to the key (i.e. change background to green).
            target.classList.add('pressed');
        }
    }
});

/** 
 * This function responds to the event of a UI keyboard key being untouched 
 * (and is logically equivalent to the physical key 'keyup' event listener function). 
 */
document.addEventListener('touchend', (event) => {
    // Get the touched web page element.
    const target = event.target;

    // Check if the released element is a key (with the 'key' class).
    if (target.classList.contains('key')) {
        // Remove the visual feedback from the key (i.e. change background back to original color).
        target.classList.remove('pressed');
    }
});

ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT Interface (Initial)


The screenshot image below depicts what the ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT web page interface is supposed to look like when the web page is initially loaded (or reloaded) by a web browser.

image_link: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/abridged_keyboard_musical_instrument_interface_p0.jpeg



ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT Interface (After Pressing Keys)


The screenshot image below depicts what the ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT web page interface could look like after the user presses one or more keys (either in succession or simultaneously). In this case, the ‘a’ and ‘s’ keys were pressed simultaneously.

image_link: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/beats_machine_interface_screenshot_p1.jpeg



ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT Use Case (Demonstration Video)


The video file linked below shows karbytes using its finished ABRIDGED_KEYBOARD_MUSICAL_INSTRUMENT application and provides some visual and auditory details about how that application works from the end user’s perspective.

video_link: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_20/main/abridged_keyboard_by_karbytes_use_case_13sep2024.mp4


This web page was last updated on 26_JANUARY_2025. The content displayed on this web page is licensed as PUBLIC_DOMAIN intellectual property.