Chapter 6
Functions
Learning Objectives
- Understand what functions are
- Learn to create and call functions
- Work with parameters and return values
- See how MixMind uses functions
What Are Functions?
Functions are reusable blocks of code that perform a specific task. They help you:
- Avoid repeating code
- Organize your code logically
- Make code easier to understand and maintain
Creating Functions
// Function declaration
function calculateMixDuration(trackCount, avgDuration) {
return trackCount * avgDuration;
}
// Call the function
let totalDuration = calculateMixDuration(10, 240);
console.log(totalDuration); // 2400
// Arrow functions (modern syntax)
const detectBPM = (audioBuffer) => {
// Analysis code here
return 128;
};
// Functions with multiple parameters
function createTransition(track1, track2, duration) {
return {
from: track1,
to: track2,
duration: duration,
type: "crossfade"
};
}
Parameters and Return Values
// Parameters are inputs
function analyzeAudio(audioBuffer, sampleRate) {
// Process audio
const bpm = detectBPM(audioBuffer);
const key = detectKey(audioBuffer);
// Return is the output
return {
bpm: bpm,
key: key,
sampleRate: sampleRate
};
}
// Using the function
const result = analyzeAudio(myAudio, 44100);
console.log(result.bpm); // 128
🎵 MixMind Connection
How MixMind Uses Functions
// Core analysis functions
async function analyzeTrack(file) {
const buffer = await loadAudio(file);
const bpm = detectBPM(buffer);
const key = detectKey(buffer);
const energy = calculateEnergy(buffer);
return { file, buffer, bpm, key, energy };
}
// Transition planning
function planTransition(track1, track2) {
const bpmDiff = Math.abs(track1.bpm - track2.bpm);
const compatible = bpmDiff < 10;
return {
compatible,
suggestedType: compatible ? "smooth" : "cut"
};
}
// Export functions
function exportMix(tracks, format) {
if (format === "mp3") {
return encodeMP3(tracks);
} else {
return encodeWAV(tracks);
}
}
Exercise 6.1: Practice
Goal: Apply what you've learned in this chapter
Try the concepts from this chapter in your browser's console or a simple HTML file. Experiment with the code examples and modify them to see what happens.
📝 Quick Reference:
Review the key concepts from this chapter and make sure you understand each one before moving to the next chapter.