Skip to content

Instantly share code, notes, and snippets.

@kush-agra
Last active December 4, 2022 21:17
Show Gist options
  • Save kush-agra/b59f59d23e80a6407781809b5e9507b7 to your computer and use it in GitHub Desktop.
Save kush-agra/b59f59d23e80a6407781809b5e9507b7 to your computer and use it in GitHub Desktop.
Play a binary string as music in javascript
// Define the audio context
var audioContext = new AudioContext();
// Define the notes and their corresponding frequencies
var notes = {
'C': 16.35,
'C#': 17.32,
'D': 18.35,
'D#': 19.45,
'E': 20.60,
'F': 21.83,
'F#': 23.12,
'G': 24.50,
'G#': 25.96,
'A': 27.50,
'A#': 29.14,
'B': 30.87
};
// Define the playNote() function
function playNote(note, duration) {
// Check if the duration is a finite number
if (!isFinite(duration)) {
// If the duration is not finite, use a default value instead
duration = 0.5;
}
// Create an oscillator to generate the musical note
var oscillator = audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = 440 * Math.pow(2, notes[note] / 12);
// Create a gain node to control the volume of the note
var gainNode = audioContext.createGain();
gainNode.gain.value = 0.25;
// Connect the oscillator and gain node to the audio context destination
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
// Start the oscillator and set its duration
oscillator.start();
oscillator.stop(audioContext.currentTime + duration);
}
// Define the playBinarySong() function
function playBinarySong(binaryString) {
// Convert the binary string into an array of ones and zeros
var binaryArray = binaryString.split('');
// Define the notes and durations for the song
var notes = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
var durations = [0.25, 0.5, 0.75, 1];
// Loop through the binary array and play each note
for (var i = 0; i < binaryArray.length; i++) {
var note = notes[i % notes.length]; // Select the next note in the sequence
var duration = durations[binaryArray[i]]; // Select the duration based on the binary value
// Play the note with the selected duration
playNote(note, duration);
}
}
// Define a binary string that represents a song
var binaryString = '01001011';
// Play the binary song
playBinarySong(binaryString);
playBinarySong('01001011100101010101011101011011');
var binaryString =
'10010010010010010010010010010010 01001011100101010101011101011011 10110101011010100101010110101010 10101010010101011010101001010101 10101010101010101010101010101010 10010010010010010010010010010010 10010010010010010010010010010010 01001011100101010101011101011011';
// Play the binary song
playBinarySong(binaryString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment