Certainly! Below is a more encapsulated JavaScript function that generates a bytebeat song, using various mathematical expressions to create interesting sounds. This example will make use of the Web Audio API to output the audio.
Bytebeat Song Function
// Create an audio context
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
function bytebeatWithSong() {
const sampleRate = audioContext.sampleRate;
const duration = 5; // Set the duration of the audio in seconds
const length = sampleRate * duration;
const buffer = audioContext.createBuffer(1, length, sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i++) {
// Create a time variable in seconds
const t = i / sampleRate;
// Example bytebeat formulas
// Feel free to modify this part to create different sounds
// Here are a few interesting formulas you can replace
// Basic example: Simple sine waves
// data[i] = Math.sin(2 * Math.PI * 440 * t) * 0.5; // A440
// A more complex bytebeat formula producing a chiptune-like effect
data[i] = ((i >> 12) ^ (i >> 8) ^ (i >> 4)) / 8.0; // Simple bytebeat expression
// Here’s another interesting pattern
// data[i] = ((i >> 8) ^ (i >> 12)) & 0x1F / 16; // Patterned sound
}
// Create a buffer source and connect it to the audio context destination
const source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start();
}
// Call the function to play the bytebeat song
bytebeatWithSong();
How to Use the Code
-
Open Your Browser Console:
- Open Google Chrome or any modern browser with developer tools.
- Right-click on the page and select "Inspect" or press
F12.
- Go to the "Console" tab.
-
Run the Code:
- Copy and paste the code above into the console.
- Press
Enter to execute it.
Customizing the Sound
You can modify the bytebeat formula inside the for loop to generate different sounds. Here are a few suggestions:
-
Simple Square Wave:
data[i] = (i & 0xFF) < 128 ? 0.5 : -0.5; // Outputs a square wave
-
Sawtooth Wave:
data[i] = (2 * (i / sampleRate - Math.floor(0.5 + i / sampleRate))) * 0.5; // Sawtooth wave
-
Different Frequencies:
Change the constants in the expressions to create various pitches.
-
Combine Expressions:
You can create more complex sounds by combining multiple mathematical operations.
Note
Due to the nature of the Web Audio API and some web browser restrictions, if you run this code, you might need to interact with the page (e.g., click a button) before it allows audio playback. Audio may not play automatically on some browsers unless initiated by user action.