### JavaScript: Load and Play Audio Tracks with Web Audio API Source: https://context7.com/dmvjs/kwyjibo/llms.txt This code example shows how to load audio buffers and schedule precise playback using the Web Audio API. It involves getting the audio context, fetching track data for specific song IDs, and using a BufferLoader to manage the loading and playback process, including tempo information. ```javascript import { BufferLoader } from './js/BufferLoader.js'; import { getContext } from './js/context.js'; import { getTracks } from './js/tracks.js'; // Get the audio context const audioContext = getContext(); // Get track URLs for two specific song IDs const trackData = getTracks(42, 137, false, false); // Returns: { bpm: 94, list: ['../music/00000042-lead.mp3', '../music/00000137-lead.mp3', ...] } // Load and play the tracks const bufferLoader = new BufferLoader( audioContext, trackData, (bufferList, tempo) => { // Create audio source const source = audioContext.createBufferSource(); source.buffer = bufferList[0]; source.connect(audioContext.destination); source.start(audioContext.currentTime); console.log(`Playing at ${tempo} BPM`); } ); bufferLoader.load(); ``` -------------------------------- ### Initialize Web Audio API Context (JavaScript) Source: https://context7.com/dmvjs/kwyjibo/llms.txt Creates and manages the Web Audio API context, essential for precise audio playback. It provides a singleton instance of the audio context and handles resuming it after user interaction. The example also demonstrates setting up a basic audio processing chain and scheduling precise playback using `audioContext.currentTime`. ```javascript import { getContext } from './js/context.js'; // Get singleton audio context instance const audioContext = getContext(); console.log(audioContext.state); // 'suspended', 'running', or 'closed' // Resume context (required after user interaction) audioContext.resume().then(() => { console.log('Audio context running'); }); // Create audio processing chain const source = audioContext.createBufferSource(); const gainNode = audioContext.createGain(); const compressor = audioContext.createDynamicsCompressor(); source.connect(gainNode); gainNode.connect(compressor); compressor.connect(audioContext.destination); // Schedule precise playback const startTime = audioContext.currentTime + 0.1; source.start(startTime) ``` -------------------------------- ### JavaScript: Generate Quantum and Cryptographic Random Numbers Source: https://context7.com/dmvjs/kwyjibo/llms.txt This example showcases methods for generating random numbers, prioritizing quantum random number generation (QRNG) for unpredictability and falling back to cryptographic randomness if necessary. It includes functions for generating random floats, integers within a range, and selecting random elements from an array. ```javascript import { quantumRandom, cryptoRandom } from './js/cryptoRandom.js'; import { QRNG } from './js/qrng.js'; // Get a quantum random float (0-1) const randomValue = quantumRandom(); console.log(randomValue); // 0.7234812... (truly random from quantum source) // Use for song selection const songIndex = Math.floor(quantumRandom() * availableSongs.length); const selectedSong = availableSongs[songIndex]; // Create a QRNG instance for more control const qrng = new QRNG(2048); // cache size qrng.onReady = () => { console.log('Quantum random number generator ready'); }; // Get quantum random integer const diceRoll = qrng.getInteger(1, 7); console.log(`Rolled: ${diceRoll}`); // 1-6 // Get random choice from array const keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; const randomKey = qrng.getChoice(keys); console.log(`Starting key: ${randomKey}`); ``` -------------------------------- ### Define and Access Song Data (JavaScript) Source: https://context7.com/dmvjs/kwyjibo/llms.txt Defines and provides access to song metadata, including tempo, key, artist, and title. It includes functions to retrieve songs by ID, remove them from a playlist, and reset the entire song library. The example shows the structure of a song object and how to interact with the song data. ```javascript import { songdata } from './js/songdata.js'; import { getSongById, removeSongFromListById, resetSongs } from './js/song.js'; // Song data structure (excerpt from full 273+ song library) // Each song has: id, bpm, key, artist, title, computedKey (optional) const exampleSong = { id: 42, bpm: 94, key: 5, artist: 'Daft Punk', title: 'Around The World', computedKey: 6 // optional: key after time-shifting }; // Get total song count console.log(`Library size: ${songdata.length} songs`); // Find song by ID const song = getSongById(42); console.log(`${song.artist} - ${song.title} [${song.key}] @ ${song.bpm}bpm`); // Remove song from active playlist (prevents replays) removeSongFromListById(42); // Reset song list (restore all songs) resetSongs() ``` -------------------------------- ### Generate Track File Paths (JavaScript) Source: https://context7.com/dmvjs/kwyjibo/llms.txt Generates audio file paths with support for lead/body distinction and automatic format detection based on the environment. It uses a utility function `file` to construct paths and `filetype` to determine the appropriate audio format (.mp3 on production, .wav on localhost). Prefetching tracks is also demonstrated for smoother playback. ```javascript import { file } from './js/utils.js'; import { filetype } from './js/filetype.js'; // Get lead (intro) track - 16 beats const leadTrack = file(42, true); console.log(leadTrack); // '../music/00000042-lead.mp3' // Get body (main) track - 64 beats const bodyTrack = file(42, false); console.log(bodyTrack); // '../music/00000042-body.mp3' // File type determined by environment console.log(filetype); // '.mp3' on production, '.wav' on localhost // Prefetch tracks for smooth playback fetch(file(42, true)); fetch(file(42, false)) ``` -------------------------------- ### JavaScript: Filter and Select Songs by Tempo and Key Source: https://context7.com/dmvjs/kwyjibo/llms.txt This snippet demonstrates how to retrieve songs based on tempo and musical key constraints, including fallback to compatible adjacent keys. It utilizes functions to set active tempo and key, and then fetches matching songs. It also shows how to select a specific song while excluding certain artists to prevent repetition. ```javascript import { getSongs, getSong } from './js/getSongs.js'; import { setActiveTempo } from './js/tempo.js'; import { setActiveKey } from './js/key.js'; // Set the active tempo and key setActiveTempo(94); setActiveKey(5); // Get all songs matching current tempo and key (including adjacent keys) const { thisKeySongs, thisTempoSongs } = getSongs(); console.log(`Found ${thisKeySongs.length} songs in compatible keys`); console.log(`Found ${thisTempoSongs.length} songs at 94 BPM`); // Get a specific song with artist exclusion to avoid repetition const nextSong = getSong(5, 'Daft Punk'); console.log(`Selected: ${nextSong.artist} - ${nextSong.id}`); // Output: { artist: 'Justice', id: 42 } ``` -------------------------------- ### Basic HTML and Body Styling for Kwyjibo DJ Source: https://github.com/dmvjs/kwyjibo/blob/main/index.html Defines fundamental styles for the HTML and body elements, setting a dark background with a repeating background image, a specific font, and text alignment for the Kwyjibo DJ application. It also includes a media query for small screens to prevent horizontal overflow. ```css html, body { font-family: 'Helvetica Neue', 'Arial Nova', Helvetica, Arial, sans-serif; color: black; text-align: center; line-height: 1.375; letter-spacing: -1px; font-size: 18px; background: black; height: 100%; margin: 0; padding: 0; background: url("bg-2048.jpg"); background-color: #090911; background-repeat: no-repeat; background-size: cover; } @media only screen and (max-width: 320px) { body { overflow-x: hidden; max-width: 100%; } } ``` -------------------------------- ### JavaScript: Navigate Musical Keys and Sort by Compatibility Source: https://context7.com/dmvjs/kwyjibo/llms.txt This snippet demonstrates functionalities for traversing musical keys, including automatic wrapping around the 12 keys and forward/reverse progression. It also includes a keySort function to arrange songs based on their harmonic compatibility, prioritizing closer keys. ```javascript import { getNextKey, keySort, setActiveKey } from './js/key.js'; // Start at key 7 setActiveKey(7); // Get the next key (forward progression) const nextKey = getNextKey(7); console.log(nextKey); // 8 // Get the previous key (reverse progression) const prevKey = getNextKey(7, true); console.log(prevKey); // 6 // Wrap around boundaries const wrapped = getNextKey(12); console.log(wrapped); // 1 // Sort songs by key compatibility const songs = [ { id: 1, key: 7, title: 'Track A' }, { id: 2, key: 8, title: 'Track B' }, { id: 3, key: 3, title: 'Track C' } ]; songs.sort(keySort); // Most compatible keys (7, 8, 6) will be sorted first ``` -------------------------------- ### Display Area Styling for Kwyjibo DJ Source: https://github.com/dmvjs/kwyjibo/blob/main/index.html Styles the 'Now Playing' and 'On Deck' sections of the Kwyjibo DJ application, creating a semi-transparent dark background with rounded corners. It also includes styles for song titles within these sections. ```css #now-playing, #on-deck { display: none; letter-spacing: 1px; text-shadow: 1px 1px 1px rgba(0,0,0,1); background: rgba(0,0,0,0.85); padding: 16px 24px; border-radius: 8px; max-width: 250px; margin-left: auto; margin-right: auto; margin-bottom: 16px; margin-top: 16px; } #now-playing h3, #on-deck h3 { margin-bottom: 8px; } #first-song-label, #second-song-label { margin-bottom: 8px; line-height: 1.1; font-size: 1.125rem; font-style: normal; } ``` -------------------------------- ### Parse Track Sequences from URL (JavaScript) Source: https://context7.com/dmvjs/kwyjibo/llms.txt Parses track sequences from URL parameters, supporting both comma-dash notation and JSON array notation. The `parseTracks` utility function handles these formats, converting them into a structured array of track pairs. It also demonstrates accessing parsed tracks directly from URL parameters. ```javascript import { parseTracks } from './js/utils.js'; import { tracksFromURL, parsedTracks } from './js/init.js'; // Parse comma-dash notation: 1,2-3,4-5,6 // Format: pairs separated by dash, songs separated by comma const url = '1,2-3,4-5,6'; const parsed = parseTracks(url); console.log(parsed); // Output: [[1,2], [3,4], [5,6]] // Parse JSON array notation const jsonUrl = '[[10,20],[30,40]]'; const jsonParsed = parseTracks(jsonUrl); console.log(jsonParsed); // Output: [[10,20], [30,40]] // Access via URL parameter // URL: ?tracks=1,2-3,4-5,6 console.log(tracksFromURL); // '1,2-3,4-5,6' console.log(parsedTracks); // [[1,2], [3,4], [5,6]] ``` -------------------------------- ### Audio Buffer Management in JavaScript Source: https://context7.com/dmvjs/kwyjibo/llms.txt Manages audio buffer sources by pre-allocating and reusing them for efficient memory usage. It involves setting buffer padding for scheduling and replenishing the buffer pool. ```javascript import { getBuffer, replenishBuffers, setBufferPadding, bufferPadding } from './js/buffers.js'; import { getContext } from './js/context.js'; // Get a pre-allocated buffer source const source = getBuffer(); source.buffer = audioBuffer; // Set your decoded audio buffer source.connect(getContext().destination); // Schedule with buffer padding (accumulated time offset) console.log(bufferPadding); // Current time offset source.start(bufferPadding); // Update padding for next track const trackDuration = audioBuffer.duration; setBufferPadding(bufferPadding + trackDuration); // Replenish buffer pool after use replenishBuffers(4); // Pre-create 4 new buffer sources ``` -------------------------------- ### Dynamic Track Selection in JavaScript Source: https://context7.com/dmvjs/kwyjibo/llms.txt Enables dynamic track selection based on user input and countdown timers. It populates select elements with songs and retrieves user-selected song IDs for playback. ```javascript import { getSelectedSongIds, loadSongsIntoSelect } from './js/tracks.js'; import { deck1Select, deck2Select } from './js/dom.js'; // Populate deck selects with available songs loadSongsIntoSelect(); // Fills