Player API Reference

Complete reference for the BeatBlocks Player API

Overview

The BeatBlocks Player API provides a comprehensive interface for loading, playing, and manipulating BeatBlock compositions. It handles audio decoding, playback scheduling, and dynamic arrangement generation.

Basic Usage

// Create a new BeatBlock player
const audioContext = new AudioContext();
const beatBlock = new BeatBlock(audioContext);

// Initialize with song data
await beatBlock.initialize({
  details: {
    title: "My BeatBlock",
    author: "BeatBlocks Creator",
    bpm: 120
  },
  layers: [
    // Layer definitions
  ],
  generationConfig: {
    seed: 12345,
    groups: ["main", "alt"],
    mutexes: ["drums", "bass"]
  },
  template: [
    // Template sections
  ]
});

// Play the composition
await beatBlock.play();

// Stop playback
beatBlock.stop();

// Download as audio file
await beatBlock.downloadSong();

Constructor

new BeatBlock(audioContext)

Creates a new BeatBlock player instance.

Parameters

  • audioContext - A Web Audio API AudioContext instance

Example

const audioContext = new AudioContext();
const beatBlock = new BeatBlock(audioContext);

Core Methods

initialize(songData)

Initializes the BeatBlock player with song data. This method loads all audio layers and generates the arrangement if needed.

Parameters

  • songData - A BeatBlockInputData object containing all composition data

Returns

Promise<void> - Resolves when initialization is complete

Example

await beatBlock.initialize({
  details: {
    title: "Example Song",
    author: "BeatBlocks Creator",
    bpm: 120
  },
  layers: [
    {
      id: "drums-1",
      name: "Basic Beat",
      loopLength: 4,
      path: "/content/example-drums-1.opus",
      volume: 1,
      loop: true,
      alignment: "start",
      groups: ["main"],
      mutex: ["drums"],
      weight: 1
    }
  ],
  generationConfig: {
    seed: 12345,
    groups: ["main", "alt"],
    mutexes: ["drums", "bass"]
  },
  template: [
    {
      length: 8,
      layerCount: 3,
      inclusions: ["drums"],
      exclusions: []
    }
  ]
});

play()

Starts playback of the BeatBlock composition.

Returns

Promise<void> - Resolves when playback has started

Example

// Start playback
await beatBlock.play();

// Check if playing
if (beatBlock.isPlaying) {
  console.log("BeatBlock is currently playing");
}

stop()

Stops playback of the BeatBlock composition.

Example

// Stop playback
beatBlock.stop();

downloadSong()

Exports the current composition as an audio file and triggers a download.

Returns

Promise<void> - Resolves when the download starts

Example

// Download the composition
await beatBlock.downloadSong();

Audio Control Methods

setMasterVolume(value)

Sets the master volume of the composition.

Parameters

  • value - Volume level (0.0 to 1.0)

Example

// Set volume to 50%
beatBlock.setMasterVolume(0.5);

getMasterVolume()

Gets the current master volume level.

Returns

number - Current volume level (0.0 to 1.0)

Example

const volume = beatBlock.getMasterVolume();
console.log(`Current volume: ${volume * 100}%`);

setBalance(value)

Sets the stereo balance of the composition.

Parameters

  • value - Balance value (-1.0 to 1.0, where -1.0 is full left, 0.0 is center, and 1.0 is full right)

Example

// Pan slightly to the right
beatBlock.setBalance(0.3);

getBalance()

Gets the current stereo balance.

Returns

number - Current balance value (-1.0 to 1.0)

Example

const balance = beatBlock.getBalance();
console.log(`Current balance: ${balance}`);

State and Information Methods

getAudioNode()

Gets the master audio node for connecting to other Web Audio nodes.

Returns

AudioNode - The master gain node

Example

// Connect to an analyzer for visualization
const analyzer = audioContext.createAnalyser();
beatBlock.getAudioNode().connect(analyzer);

getAudioContext()

Gets the AudioContext used by the player.

Returns

AudioContext - The Web Audio API context

getCurrentStep()

Gets the current playback step within the current section.

Returns

number - Current step index

getCurrentSection()

Gets the current section index in the arrangement.

Returns

number - Current section index

getTotalSections()

Gets the total number of sections in the arrangement.

Returns

number - Total number of sections

getDetails()

Gets the composition details (title, author, BPM).

Returns

Details - Composition details object

Example

const details = beatBlock.getDetails();
console.log(`Now playing: ${details.title} by ${details.author} at ${details.bpm} BPM`);

getBpm()

Gets the composition's tempo in beats per minute.

Returns

number - BPM value

getPlaybackProgress()

Gets the current playback progress as a percentage.

Returns

number - Progress percentage (0-100)

Example

// Update progress bar
function updateProgress() {
  const progress = beatBlock.getPlaybackProgress();
  progressBar.style.width = `${progress}%`;
  
  if (beatBlock.isPlaying) {
    requestAnimationFrame(updateProgress);
  }
}

updateProgress();

getVersion()

Gets the BeatBlock player version.

Returns

string - Version string

Event Handling

on(event, callback)

Registers an event listener for BeatBlock player events.

Parameters

  • event - Event name ('info', 'error', etc.)
  • callback - Function to call when the event occurs

Example

// Listen for info events
beatBlock.on('info', (message) => {
  console.log(`BeatBlock info: ${message}`);
});

// Listen for errors
beatBlock.on('error', (errorMessage) => {
  console.error(`BeatBlock error: ${errorMessage}`);
});

Complete Example

A complete example of using the BeatBlocks Player API:

// Initialize audio context
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
const beatBlock = new BeatBlock(audioContext);

// Set up event listeners
beatBlock.on('info', (message) => {
  console.log(`BeatBlock: ${message}`);
});

beatBlock.on('error', (error) => {
  console.error(`BeatBlock error: ${error}`);
});

// Load song data
async function loadAndPlay() {
  try {
    // Fetch song data from server or use inline data
    const response = await fetch('/api/beatblocks/song/123');
    const songData = await response.json();
    
    // Initialize the player
    await beatBlock.initialize(songData);
    
    // Update UI with song details
    const details = beatBlock.getDetails();
    document.getElementById('song-title').textContent = details.title;
    document.getElementById('song-author').textContent = details.author;
    document.getElementById('song-bpm').textContent = `${details.bpm} BPM`;
    
    // Set up visualization
    const analyzer = audioContext.createAnalyser();
    beatBlock.getAudioNode().connect(analyzer);
    setupVisualizer(analyzer);
    
    // Set up progress tracking
    function updateProgress() {
      const progress = beatBlock.getPlaybackProgress();
      document.getElementById('progress-bar').style.width = `${progress}%`;
      
      if (beatBlock.isPlaying) {
        requestAnimationFrame(updateProgress);
      }
    }
    
    // Set up play/pause button
    const playButton = document.getElementById('play-button');
    playButton.addEventListener('click', async () => {
      if (audioContext.state === 'suspended') {
        await audioContext.resume();
      }
      
      if (beatBlock.isPlaying) {
        beatBlock.stop();
        playButton.textContent = 'Play';
      } else {
        await beatBlock.play();
        playButton.textContent = 'Pause';
        updateProgress();
      }
    });
    
    // Set up volume control
    const volumeSlider = document.getElementById('volume-slider');
    volumeSlider.addEventListener('input', () => {
      const volume = parseFloat(volumeSlider.value);
      beatBlock.setMasterVolume(volume);
    });
    
    // Set up download button
    const downloadButton = document.getElementById('download-button');
    downloadButton.addEventListener('click', async () => {
      await beatBlock.downloadSong();
    });
    
    console.log(`BeatBlock player v${beatBlock.getVersion()} ready`);
  } catch (error) {
    console.error('Failed to load BeatBlock:', error);
  }
}

// Start loading when the page is ready
document.addEventListener('DOMContentLoaded', loadAndPlay);