how to play music intervals melodically in javascript

To play music intervals melodically in JavaScript, we need to first define the intervals we want to play in terms of musical notes. We can do this by creating an array of notes, where each element represents a note, and the distance between consecutive elements represents the interval (e.g., the distance between "C" and "D" is a whole step, while the distance between "C" and "C#"/"Db" is a half step).

Once we have this array, we can use the Web Audio API to create an oscillator node, connect it to the audio output, and set its frequency based on the interval we want to play. We can also add some envelope and filter automation to add more expression to the melody.

Here is some sample code that demonstrates how to play a melody using intervals in JavaScript:

index.tsx
// Define the musical notes
const notes = ["C", "D", "E", "F", "G", "A", "B"];

// Define the intervals for a simple melody
const intervals = [0, 2, 4, 5, 4, 2, 0];

// Create an audio context and oscillator node
const audioContext = new AudioContext();
const oscillator = audioContext.createOscillator();

// Set oscillator parameters
oscillator.type = "sawtooth";
oscillator.frequency.value = 440; // starting pitch (A440)

// Create a gain node and connect it to the oscillator
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);

// Create a lowpass filter and connect it to the gain node
const filterNode = audioContext.createBiquadFilter();
filterNode.type = "lowpass";
gainNode.connect(filterNode);

// Connect the filter node to the audio output
filterNode.connect(audioContext.destination);

// Set the envelope parameters
gainNode.gain.setValueAtTime(0, audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(1, audioContext.currentTime + 0.1);
gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 0.5);

// Play the melody
const startTime = audioContext.currentTime + 0.1; // start after 0.1 seconds
for (let i = 0; i < intervals.length; i++) {
  const noteIndex = (notes.indexOf("C") + intervals[i]) % notes.length; // get the note index
  const frequency = 440 * Math.pow(2, noteIndex / 12); // calculate the frequency
  oscillator.frequency.setValueAtTime(frequency, startTime + i * 0.5); // play each note for 0.5 seconds
}
1486 chars
39 lines

This code plays a simple melody using the intervals in the intervals array. We create an oscillator node with a sawtooth wave, and connect it to a gain node with an envelope that fades in and out. We also add a lowpass filter to give the melody a warmer tone.

To play a different melody, we can simply change the contents of the intervals array. We can also experiment with different oscillator types, filter settings, and envelope shapes to create different sounds and moods.

gistlibby LogSnag