### Install Peaks.js with npm Source: https://context7.com/bbc/peaks.js/llms.txt Install Peaks.js and its peer dependencies using npm. ```bash npm install --save peaks.js konva waveform-data ``` -------------------------------- ### Start Playback with player.play() Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md Starts media playback from the current position. This method may return a Promise that resolves when playback begins. A 'player.playing' event should be emitted upon successful start. ```javascript play() { return this.externalPlayer.play().then(() => { this.state = 'playing'; this.eventEmitter.emit('player.playing', this.getCurrentTime()); }); } ``` -------------------------------- ### instance.player.play() Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Starts playback of the audio. ```APIDOC ## instance.player.play() ### Description Starts audio playback. ### Request Example ```javascript instance.player.play(); ``` ``` -------------------------------- ### player.play() Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md Starts playback from the current playback position. This function may return a Promise which resolves when playback actually starts. A player.playing event should be emitted when playback starts. ```APIDOC ## player.play() ### Description Starts playback from the current playback position. ### Method `play()` ### Returns A `Promise` that resolves when playback starts. ``` -------------------------------- ### view.getStartTime() Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Returns the start time, in seconds, of the overview or zoomable waveform view. ```APIDOC ## `view.getStartTime()` ### Description Returns the start time, in seconds, of the overview or zoomable waveform view. Note that the start time may not be exactly the same value you set when calling [`view.setStartTime()`](#viewsetstarttimetime). This is because the time is rounded to a number of pixels at the view's zoom level. ### Response #### Success Response (200) - **startTime** (number) - The start time in seconds. ### Request Example ```js const view = instance.views.getView('zoomview'); const startTime = view.getStartTime(); // seconds ``` ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/bbc/peaks.js/blob/master/README.md Commands to clone the Peaks.js repository and install its Node.js dependencies. ```bash git clone git@github.com:bbc/peaks.js.git cd peaks.js npm install ``` -------------------------------- ### Install Peaks.js with npm Source: https://github.com/bbc/peaks.js/blob/master/README.md Install Peaks.js and its peer dependencies, Konva and waveform-data, using npm. This is recommended for use with module bundlers. ```bash npm install --save peaks.js npm install --save konva npm install --save waveform-data ``` -------------------------------- ### Build Peaks.js Locally Source: https://github.com/bbc/peaks.js/blob/master/doc/faq.md Clone the repository, install dependencies, and build the project locally to test pre-release versions. ```bash git clone git@github.com:bbc/peaks.js cd peaks.js npm install npm run build ``` -------------------------------- ### view.setStartTime() Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Sets the start time for the view's visible range. ```APIDOC ## view.setStartTime() ### Description Sets the start time for the view's visible range. ### Parameters - **time** (number) - Required - The start time in seconds. ### Request Example ```javascript zoomView.setStartTime(60); ``` ``` -------------------------------- ### Get Waveform Start Time Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Retrieves the start time in seconds for the overview or zoomable waveform view. The value may be rounded based on the current zoom level. ```javascript const view = instance.views.getView('zoomview'); const startTime = view.getStartTime(); // seconds ``` -------------------------------- ### Build Peaks.js Library Source: https://github.com/bbc/peaks.js/blob/master/README.md Command to build the Peaks.js library after installing dependencies. ```bash npm run build ``` -------------------------------- ### Play Media Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Starts media playback from the current time position. ```javascript instance.player.play(); ``` -------------------------------- ### Set Waveform Start Time Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Changes the start time in seconds for the zoomable waveform view. Not available on the overview waveform. ```javascript const view = instance.views.getView('zoomview'); view.setStartTime(6.0); // seconds ``` -------------------------------- ### External Player Integration with Tone.js Source: https://github.com/bbc/peaks.js/blob/master/demo/external-player.html Sets up an external player using Tone.js and integrates it with Peaks.js. This example requires Tone.js to be loaded. It defines player methods like init, destroy, setSource, play, pause, seek, and provides event emission for player state updates. ```javascript function getSources() { return [ { title: 'Tree of Life', mediaUrl: '/TOL_6min_720p_download.mp3' }, { title: 'Desert Island Discs', mediaUrl: '/sample.mp3' }, { title: 'BBC Sound Effect (Cars)', mediaUrl: '/07023003.mp3' } ]; } function fetchAndDecode(audioContext, url) { // Load audio file into an AudioBuffer return fetch(url) .then(function(response) { return response.arrayBuffer(); }) .then(function(buffer) { return audioContext.decodeAudioData(buffer); }); } function fetchAndUpdateWaveform(peaksInstance, audioContext, source) { return fetchAndDecode(audioContext, source.mediaUrl) .then(function(audioBuffer) { // Update the Peaks.js waveform view with the new AudioBuffer. // The AudioBuffer is passed through to the external player's setSource() // method, to update the player. peaksInstance.setSource({ webAudio: { audioBuffer: audioBuffer, scale: 128, multiChannel: false } }, function(error) { if (error) { console.error('setSource error', error); } }); }); } (async function(Peaks) { const audioContext = Tone.context; fetchAndDecode(audioContext, "/TOL_6min_720p_download.mp3") .then(function(audioBuffer) { const player = { externalPlayer: new Tone.Player(audioBuffer).toDestination(), eventEmitter: null, init: function(eventEmitter) { this.eventEmitter = eventEmitter; this.externalPlayer.sync(); this.externalPlayer.start(); Tone.Transport.scheduleRepeat(() => { const time = this.getCurrentTime(); eventEmitter.emit('player.timeupdate', time); if (time >= this.getDuration()) { Tone.Transport.stop(); } }, 0.25); return Promise.resolve(); }, destroy: function() { Tone.context.dispose(); this.externalPlayer = null; this.eventEmitter = null; }, setSource: function(opts) { if (this.isPlaying()) { this.pause(); } // Update the Tone.js Player object with the new AudioBuffer this.externalPlayer.buffer.set(opts.webAudio.audioBuffer); return Promise.resolve(); }, play: function() { return Tone.start().then(() => { Tone.Transport.start(); this.eventEmitter.emit('player.playing', this.getCurrentTime()); }); }, pause: function() { Tone.Transport.pause(); this.eventEmitter.emit('player.pause', this.getCurrentTime()); }, isPlaying: function() { return Tone.Transport.state === "started"; }, seek: function(time) { Tone.Transport.seconds = time; this.eventEmitter.emit('player.seeked', this.getCurrentTime()); this.eventEmitter.emit('player.timeupdate', this.getCurrentTime()); }, isSeeking: function() { return false; }, getCurrentTime: function() { return Tone.Transport.seconds; }, getDuration: function() { return this.externalPlayer.buffer.duration; } }; const options = { zoomview: { container: document.getElementById('zoomview-container') }, overview: { container: document.getElementById('overview-container') }, player: player, webAudio: { audioBuffer: audioBuffer, scale: 128, multiChannel: false }, keyboard: true, showPlayheadTime: true, zoomLevels: [128, 256, 512, 1024, 2048, 4096] }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log('Peaks instance ready'); document.querySelector('["data-action"="play"]')?.addEventListener('click', function() { peaksInstance.player.play(); }); document.querySelector('["data-action"="pause"]')?.addEventListener('click', function() { peaksInstance.player.pause(); }); document.querySelector('button["data-action"="seek"]')?.addEventListener('click', function(event) { const time = document.getElementById('seek-time').value; const seconds = parseFloat(time); if (!Number.isNaN(seconds)) { peaksInstance.player.seek(seconds); } }); document.querySelector('["data-action"="zoom-in"]')?.addEventListener('click', function() { peaksInstance.zoom.zoomIn(); }); document.querySelector('["data-action"="zoom-out"]')?.addEventListener('click', function() { peaksInstance.zoom.zoomOut(); }); document.querySelector('["data-action"="play-segment"]')?.addEventListener('click', function () { const start = document.getElementById('segment-start').value; const startInSeconds = parseFloat(start); const end = document.getElementById('segment-end').value; const endInSeconds = parseFloat(end); if (!Number.isNaN(startInSeconds) && !Number.isNaN(endInSeconds)) { peaksInstance.player.play({ start: startInSeconds, end: endInSeconds }); } }); }); }); })(Peaks); ``` -------------------------------- ### Initialize Peaks.js with Overlay Segments Source: https://github.com/bbc/peaks.js/blob/master/demo/overlay-segments.html Configure Peaks.js with options for zoomview, overview, media, and detailed segment styling for overlays. This setup is essential for displaying and customizing segment overlays. ```javascript var options = { zoomview: { container: document.getElementById('zoomview-container'), playheadClickTolerance: 3 }, overview: { container: document.getElementById('overview-container') }, mediaElement: document.getElementById('audio'), dataUri: { arraybuffer: '/TOL_6min_720p_download.dat', json: '/TOL_6min_720p_download.json' }, keyboard: true, pointMarkerColor: '#006eb0', showPlayheadTime: true, waveformCache: true, zoomLevels: [512, 1024, 2048, 4096], segmentOptions: { markers: false, overlay: true, waveformColor: '#ff851b', overlayColor: '#ff0000', overlayOpacity: 0.3, overlayBorderColor: '#ff0000', overlayBorderWidth: 2, overlayCornerRadius: 5, overlayOffset: 40, overlayLabelAlign: 'left', overlayLabelVerticalAlign: 'top', overlayLabelPadding: 8, overlayLabelColor: '#000000', overlayFontFamily: 'sans-serif', overlayFontSize: 14, overlayFontStyle: 'normal' }, createSegmentLabel: function() { return null; }, }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log("Peaks instance ready"); // ... other initializations }); ``` -------------------------------- ### Resize Marker with Viewport Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md Implement the `fitToView` method to adjust the marker's dimensions when the waveform view is resized. This example updates the points of the marker's line. ```javascript fitToView() { const layer = this._options.layer; const height = layer.getHeight(); this._line.points([0.5, 0, 0.5, height]); } ``` -------------------------------- ### view.setStartTime(time) Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Changes the start time, in seconds, of the zoomable waveform view. Not available on the overview waveform. ```APIDOC ## `view.setStartTime(time)` ### Description Changes the start time, in seconds, of the zoomable waveform view. Note that this method is not available on the overview waveform. ### Parameters #### Path Parameters - **time** (number) - Required - The desired start time in seconds. ### Request Example ```js const view = instance.views.getView('zoomview'); view.setStartTime(6.0); // seconds ``` ``` -------------------------------- ### Initialize a Custom Point Marker Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md Implement the `init` method to create Konva objects for a marker and add them to a group. This example creates a vertical line and a rectangular handle. ```javascript class CustomPointMarker { constructor(options) { this._options = options; } init(group) { const layer = this._options.layer; const height = layer.getHeight(); this._handle = new Konva.Rect({ x: -20, y: 0, width: 40, height: 20, fill: this._options.color }); this._line = new Konva.Line({ points: [0.5, 0, 0.5, height], // x1, y1, x2, y2 stroke: options.color, strokeWidth: 1 }); group.add(this._handle); group.add(this._line); } } ``` -------------------------------- ### Initialize Peaks.js Instance Source: https://github.com/bbc/peaks.js/blob/master/demo/index.html Initializes a new Peaks.js instance with specified options and handles initialization errors. This is the starting point for using the library. ```javascript var options = { zoomview: { container: document.getElementById('zoomview-container'), playheadClickTolerance: 3 }, overview: { container: document.getElementById('overview-container') }, mediaElement: document.getElementById('audio'), dataUri: { arraybuffer: '/TOL_6min_720p_download.dat', json: '/TOL_6min_720p_download.json' }, keyboard: true, pointMarkerColor: '#006eb0', showPlayheadTime: true, waveformCache: true, zoomLevels: [512, 1024, 2048, 4096] }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log("Peaks instance ready"); }); ``` -------------------------------- ### Handle player canplay event Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Register a callback to be executed when the media is ready to start playing. This event is equivalent to the HTMLMediaElement 'canplay' event. ```javascript instance.on('player.canplay', function() { console.log('Playback ready'); }); ``` -------------------------------- ### Handle Point Drag Start Event Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Detect when a user begins dragging a point marker using the 'points.dragstart' event. The event includes the point being dragged and the associated MouseEvent. ```javascript instance.on('points.dragstart', function(event) { console.log(`Start dragging point: ${event.point.id}`); }); ``` -------------------------------- ### Integrate Local Peaks.js Build Source: https://github.com/bbc/peaks.js/blob/master/doc/faq.md After building locally, install Peaks.js via npm and then copy the built files into your project's node_modules to use the local build. ```bash npm install peaks.js cp ../peaks.js/peaks.js.d.ts node_modules/peaks.js cp ../peaks.js/dist/*.js node_modules/peaks.js/dist cp ../peaks.js/dist/*.map node_modules/peaks.js/dist ``` -------------------------------- ### Implement Custom Point and Segment Markers Source: https://context7.com/bbc/peaks.js/llms.txt Provides an example of creating custom marker classes using Konva for points and segments. This requires using the ESM or external builds of Peaks.js. The `init` method is called when the marker is created, `fitToView` when the view changes, and `update` when marker properties change. ```javascript import Konva from 'konva'; import Peaks from 'peaks.js'; class DiamondPointMarker { constructor(options) { this._options = options; } init(group) { const height = this._options.layer.getHeight(); this._line = new Konva.Line({ points: [0.5, 0, 0.5, height], stroke: this._options.color, strokeWidth: 1 }); this._diamond = new Konva.RegularPolygon({ x: 0, y: 14, sides: 4, radius: 8, fill: this._options.color, rotation: 45 }); this._diamond.on('mouseenter', () => { this._diamond.fill('#fff'); this._options.layer.draw(); }); this._diamond.on('mouseleave', () => { this._diamond.fill(this._options.color); this._options.layer.draw(); }); group.add(this._line); group.add(this._diamond); } fitToView() { const height = this._options.layer.getHeight(); this._line.points([0.5, 0, 0.5, height]); } update(options) { if (options.color) { this._diamond.fill(options.color); this._line.stroke(options.color); } } destroy() { /* cleanup if needed */ } } Peaks.init({ // ...container and media options... createPointMarker: (options) => new DiamondPointMarker(options), createSegmentMarker: (options) => { // return null to hide markers on overview if (options.view === 'overview') return null; return new DiamondPointMarker(options); // reuse or define another class } }, function(err, peaks) { /* ready */ }); ``` -------------------------------- ### Control Playback and Zoom Source: https://github.com/bbc/peaks.js/blob/master/demo/cue-events.html Provides examples for controlling playback, including seeking to a specific time, and controlling zoom levels of the Peaks.js waveform. ```javascript document.querySelector('button[data-action="seek"]').addEventListener('click', function(event) { var time = document.getElementById('seek-time').value; var seconds = parseFloat(time); if (!Number.isNaN(seconds)) { peaksInstance.player.seek(seconds); } }); document.querySelector('button[data-action="zoom-in"]').addEventListener('click', function() { peaksInstance.zoom.zoomIn(); }); document.querySelector('button[data-action="zoom-out"]').addEventListener('click', function() { peaksInstance.zoom.zoomOut(); }); ``` -------------------------------- ### Handle Segment Drag Start Event Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Use the 'segments.dragstart' event to detect when a user begins dragging a segment or its start/end markers. The event object provides details about the segment being dragged and whether a marker or the entire segment is involved. ```javascript instance.on('segments.dragstart', function(event) { console.log(`Start dragging segment: ${event.segment.id}`); }); ``` -------------------------------- ### Initialize External Media Player with Promise Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md The `init` method for an external player should accept an event emitter and return a Promise to handle asynchronous initialization. ```javascript init(eventEmitter) { this.eventEmitter = eventEmitter; this.state = 'paused'; this.interval = null; // Initialize the external player this.externalPlayer = new MediaPlayer(); return Promise.resolve(); } ``` -------------------------------- ### Get View Reference Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Returns a reference to a specific waveform view ('zoomview' or 'overview'). Returns null if the view is not available. The name can be omitted if only one view exists. ```javascript const view = instance.views.getView('zoomview'); ``` -------------------------------- ### Initialize Peaks.js with Cue Events Enabled Source: https://github.com/bbc/peaks.js/blob/master/demo/cue-events.html Initializes the Peaks.js player with various options, including enabling cue events. This setup is required to trigger segment and point enter/exit events. ```javascript var options = { zoomview: { container: document.getElementById('zoomview-container') }, overview: { container: document.getElementById('overview-container') }, mediaElement: document.getElementById('audio'), dataUri: { arraybuffer: '/TOL_6min_720p_download.dat', json: '/TOL_6min_720p_download.json' }, keyboard: true, pointMarkerColor: '#006eb0', showPlayheadTime: true, emitCueEvents: true }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log("Peaks instance ready"); // ... rest of the event listeners and initializations }); ``` -------------------------------- ### Custom player initialization with Promises Source: https://github.com/bbc/peaks.js/blob/master/doc/migration-guide.md For custom player objects, the `init` function must now return a `Promise` to support asynchronous initialization. If not using a custom player, no changes are needed. ```javascript class CustomPlayer { init(eventEmitter) { this.eventEmitter = eventEmitter; this.state = 'paused'; this.interval = null; // Initialize the external player this.externalPlayer = new MediaPlayer(); // Returning a promise is now required return Promise.resolve(); }, // ... other player methods, as shown in customizing.md }; const options = { // Add other options, as needed. player: player }; Peaks.init(options, function(err, instance) { // Use the Peaks.js instance here }); ``` -------------------------------- ### Remove segments by start time Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Delete segments based on their start time. Optionally, you can specify an `endTime` to remove only segments that match both start and end times. Returns the count of removed segments. ```javascript instance.segments.add([ { startTime: 10, endTime: 12 }, { startTime: 10, endTime: 20 } ]); // Remove both segments as they start at 10 instance.segments.removeByTime(10); // Remove only the first segment instance.segments.removeByTime(10, 12); ``` -------------------------------- ### View audiowaveform Manual Source: https://github.com/bbc/peaks.js/blob/master/README.md Access the manual page for the audiowaveform command-line tool to explore all available options. ```bash man audiowaveform ``` -------------------------------- ### Overview Waveform Event Listeners Source: https://github.com/bbc/peaks.js/blob/master/demo/overlay-segments.html Sets up event listeners for the overview waveform, including click, dblclick, and contextmenu events. These allow for custom interactions with the broader waveform overview. ```javascript peaksInstance.on('overview.click', function(event) { console.log('overview.click:', event); }); peaksInstance.on('overview.dblclick', function(event) { console.log('overview.dblclick:', event); }); peaksInstance.on('overview.contextmenu', function(event) { event.evt.preventDefault(); console.log('overview.contextmenu:', event); }); ``` -------------------------------- ### instance.zoom.getZoom() Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Gets the current zoom level. ```APIDOC ## instance.zoom.getZoom() ### Description Returns the current zoom level. ### Response - **zoomLevel** (number) - The index of the current zoom level. ### Request Example ```javascript const currentZoom = instance.zoom.getZoom(); console.log('Current zoom level:', currentZoom); ``` ``` -------------------------------- ### Initialize Peaks.js with options Source: https://context7.com/bbc/peaks.js/llms.txt Initialize a new Peaks instance with various configuration options, including zoom view, overview, media element, data URI, segments, and points. The callback receives an error object or the Peaks instance. ```html
``` -------------------------------- ### instance.player.getDuration() Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Gets the total duration of the audio in seconds. ```APIDOC ## instance.player.getDuration() ### Description Returns the total duration of the audio in seconds. ### Response - **duration** (number) - The total duration of the audio in seconds. ### Request Example ```javascript const duration = instance.player.getDuration(); console.log('Duration:', duration); ``` ``` -------------------------------- ### instance.player.getCurrentTime() Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Gets the current playback time in seconds. ```APIDOC ## instance.player.getCurrentTime() ### Description Returns the current playback time in seconds. ### Response - **currentTime** (number) - The current playback time in seconds. ### Request Example ```javascript const currentTime = instance.player.getCurrentTime(); console.log('Current time:', currentTime); ``` ``` -------------------------------- ### Create Overview Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Creates a non-zoomable waveform view (overview) within the specified container element. ```javascript const container = document.getElementById('overview-container'); const view = instance.views.createOverview(container); ``` -------------------------------- ### Initialize Peaks.js with Web Audio API Source: https://github.com/bbc/peaks.js/blob/master/demo/webaudio.html Initializes Peaks.js using the Web Audio API for waveform computation. Configure zoom levels, containers, and enable keyboard interaction. Ensure the AudioContext is available in the browser. ```javascript var AudioContext = window.AudioContext || window.webkitAudioContext; var audioContext = new AudioContext(); var audioElement = document.getElementById('audio'); var options = { zoomview: { container: document.getElementById('zoomview-container') }, overview: { container: document.getElementById('overview-container') }, mediaElement: audioElement, webAudio: { audioContext: audioContext, scale: 128, multiChannel: false }, keyboard: true, pointMarkerColor: '#006eb0', showPlayheadTime: true, zoomLevels: [128, 256, 512, 1024, 2048, 4096] }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log('Peaks instance ready'); // Event listeners for UI controls document.querySelector('["data-action="zoom-in"]').addEventListener('click', function() { peaksInstance.zoom.zoomIn(); }); document.querySelector('["data-action="zoom-out"]').addEventListener('click', function() { peaksInstance.zoom.zoomOut(); }); document.querySelector('button["data-action="add-segment"]').addEventListener('click', function() { peaksInstance.segments.add({ startTime: peaksInstance.player.getCurrentTime(), endTime: peaksInstance.player.getCurrentTime() + 2, labelText: "Test segment", editable: true }); }); document.querySelector('button["data-action="add-point"]').addEventListener('click', function() { peaksInstance.points.add({ time: peaksInstance.player.getCurrentTime(), labelText: "Test point", editable: true }); }); document.querySelector('button["data-action="log-data"]').addEventListener('click', function(event) { renderSegments(peaksInstance); renderPoints(peaksInstance); }); document.querySelector('button["data-action="seek"]').addEventListener('click', function(event) { var time = document.getElementById('seek-time').value; var seconds = parseFloat(time); if (!Number.isNaN(seconds)) { peaksInstance.player.seek(seconds); } }); document.querySelector('body').addEventListener('click', function(event) { var element = event.target; var action = element.getAttribute('data-action'); var id = element.getAttribute('data-id'); if (action === 'play-segment') { var segment = peaksInstance.segments.getSegment(id); peaksInstance.player.playSegment(segment); } else if (action === 'remove-point') { peaksInstance.points.removeById(id); } else if (action === 'remove-segment') { peaksInstance.segments.removeById(id); } }); }); })(peaks); ``` -------------------------------- ### Get Media Duration Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Returns the total duration of the media in seconds. ```javascript const duration = instance.player.getDuration(); ``` -------------------------------- ### Initialize Points Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Define points with a specific time, editability, color, and label text. Points can be used to mark specific moments in the audio. ```javascript points: [ { time: 150, editable: true, color: "#00ff00", labelText: "A point" }, { time: 160, editable: true, color: "#00ff00", labelText: "Another point" } ] ``` -------------------------------- ### Peaks.init(options, callback) Source: https://context7.com/bbc/peaks.js/llms.txt Initializes a new Peaks instance with specified options and a callback function. The callback receives an error object if initialization fails, or the Peaks instance upon success. ```APIDOC ## Peaks.init(options, callback) — Initialize a Peaks instance Creates and initializes a new Peaks instance. The callback receives `(err, peaks)`; `peaks` is `null` on failure. Multiple independent instances can coexist on the same page. ### Parameters #### options - **zoomview** (object) - Configuration for the zoomable waveform view. - **container** (HTMLElement) - The DOM element to contain the zoom view. - **waveformColor** (string) - Color of the waveform. - **playedWaveformColor** (string) - Color of the played portion of the waveform. - **showPlayheadTime** (boolean) - Whether to display the playhead time. - **overview** (object) - Configuration for the overview waveform view. - **container** (HTMLElement) - The DOM element to contain the overview. - **waveformColor** (string) - Color of the overview waveform. - **highlightColor** (string) - Color used to highlight the current view. - **mediaElement** (HTMLMediaElement) - The audio element to use for playback. - **dataUri** (object) - URI for pre-computed waveform data. - **arraybuffer** (string) - URL to the waveform data file (e.g., `.dat`). - **webAudio** (object) - Configuration for generating waveform data in the browser using Web Audio API. - **audioContext** (AudioContext) - An existing AudioContext instance. - **scale** (number) - Scaling factor for waveform data. - **multiChannel** (boolean) - Whether to generate per-channel waveforms. - **audioBuffer** (AudioBuffer) - A pre-decoded AudioBuffer. - **zoomLevels** (array) - An array of integers representing available zoom levels. - **keyboard** (boolean) - Enable keyboard controls. - **nudgeIncrement** (number) - The increment for nudging the playhead. - **emitCueEvents** (boolean) - Whether to emit cue events. - **segments** (array) - An array of segment objects to initialize. - **id** (string) - Unique identifier for the segment. - **startTime** (number) - Start time of the segment in seconds. - **endTime** (number) - End time of the segment in seconds. - **labelText** (string) - Text label for the segment. - **editable** (boolean) - Whether the segment is editable. - **color** (string) - Color of the segment. - **points** (array) - An array of point objects to initialize. - **id** (string) - Unique identifier for the point. - **time** (number) - Time of the point in seconds. - **labelText** (string) - Text label for the point. - **color** (string) - Color of the point. - **editable** (boolean) - Whether the point is editable. - **logger** (function) - A function to handle logging messages. #### callback - **err** (Error) - An error object if initialization fails. - **peaks** (PeaksInstance) - The initialized Peaks instance, or null if an error occurred. ### Request Example ```html
``` -------------------------------- ### Get Media Duration with player.getDuration() Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md Returns the total duration of the media in seconds. ```javascript getDuration() { return this.externalPlayer.duration; } ``` -------------------------------- ### Initialize Peaks.js and Handle Media URL Changes Source: https://github.com/bbc/peaks.js/blob/master/demo/set-source.html This snippet initializes Peaks.js with various configuration options and demonstrates how to dynamically change the media source using different data formats (dataUri, webAudio, waveformData). It includes event handlers for zoom controls and a select element to switch audio sources. ```javascript (function(Peaks) { var AudioContext = window.AudioContext || window.webkitAudioContext; var audioContext = new AudioContext(); function requestWaveformData(url) { return fetch(url) .then(function(response) { return response.arrayBuffer(); }); } function createSources(waveformData) { return [ { title: 'Tree of Life', mediaUrl: '/TOL_6min_720p_download.mp3', dataUri: { arraybuffer: 'TOL_6min_720p_download.dat', json: 'TOL_6min_720p_download.json' } }, { title: 'Desert Island Discs', mediaUrl: '/sample.mp3', webAudio: { audioContext: audioContext }, zoomLevels: [128, 256] }, { title: 'BBC Sound Effect (Cars)', mediaUrl: '/07023003.mp3', waveformData: { arraybuffer: waveformData } } ]; } function createPeaksInstance(options) { return new Promise(function(resolve, reject) { Peaks.init(options, function(err, peaksInstance) { if (err) { reject(err); } else { console.log('Peaks instance ready'); return resolve(peaksInstance); } }); }); } function bindEventHandlers(peaksInstance, sources) { document.querySelector('[data-action="zoom-in"]').addEventListener('click', function() { peaksInstance.zoom.zoomIn(); }); document.querySelector('[data-action="zoom-out"]').addEventListener('click', function() { peaksInstance.zoom.zoomOut(); }); var select = document.getElementById('select-audio'); for (var i = 0; i < sources.length; i++) { select.options[i] = new Option(sources[i].title, i); } select.addEventListener('change', function(event) { var source = sources[event.target.value]; peaksInstance.setSource(source, function(error) { if (error) { console.error('setSource error', error); } }); }); } function errorHandler(err) { console.error(err.message); } var options = { zoomview: { container: document.getElementById('zoomview-container') }, overview: { container: document.getElementById('overview-container') }, mediaElement: document.getElementById('audio'), dataUri: { arraybuffer: '/TOL_6min_720p_download.dat', json: '/TOL_6min_720p_download.json' }, keyboard: true, pointMarkerColor: '#006eb0', showPlayheadTime: true, zoomLevels: [512, 1024, 2048] }; createPeaksInstance(options) .then(function(peaksInstance) { requestWaveformData('/07023003-2channel.dat') .then(function(waveformData) { return createSources(waveformData); }) .then(function(sources) { bindEventHandlers(peaksInstance, sources); }, errorHandler); }, errorHandler); })(peaks); ``` -------------------------------- ### Retrieve all segments Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Get an array containing all segments currently present on the waveform timeline. ```javascript const segments = instance.segments.getSegments(); ``` -------------------------------- ### Get Scrollbar Reference Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Returns a reference to the scrollbar object, or null if no scrollbar is present. ```javascript const scrollbar = instance.views.getScrollbar(); ``` -------------------------------- ### instance.segments.removeByTime(startTime[, endTime]) Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Removes segments based on their start time, and optionally their end time. ```APIDOC ## `instance.segments.removeByTime(startTime[, endTime])` ### Description Removes segments based on their start time, and optionally their end time. ### Parameters * `startTime` (number): The start time in seconds of segments to remove. * `endTime` (number, optional): The end time in seconds of segments to remove. If provided, only segments matching both `startTime` and `endTime` are removed. ### Returns * `number`: The number of segments deleted. ### Request Example ```js instance.segments.add([ { startTime: 10, endTime: 12 }, { startTime: 10, endTime: 20 } ]); // Remove both segments as they start at 10 instance.segments.removeByTime(10); // Remove only the first segment instance.segments.removeByTime(10, 12); ``` ``` -------------------------------- ### Get all points from the timeline Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Retrieve an array containing all points currently present on the waveform timeline. ```javascript const points = instance.points.getPoints(); ``` -------------------------------- ### Get Current Playback Time with player.getCurrentTime() Source: https://github.com/bbc/peaks.js/blob/master/doc/customizing.md Returns the current playback position of the media in seconds. ```javascript getCurrentTime() { return this.externalPlayer.currentTime; } ``` -------------------------------- ### Initialize Zoomable Waveform with Peaks.js Source: https://github.com/bbc/peaks.js/blob/master/demo/zoomable-waveform.html Initializes Peaks.js with options for a zoomable waveform, including container IDs, colors, and Web Audio API settings. Handles initialization errors and logs success. ```javascript (function(Peaks) { var AudioContext = window.AudioContext || window.webkitAudioContext; var audioContext = new AudioContext(); var options = { zoomview: { container: document.getElementById('zoomview-container'), waveformColor: '#00e180', playedWaveformColor: '#bc6dfd', showPlayheadTime: true }, mediaElement: document.getElementById('audio'), webAudio: { audioContext: audioContext, scale: 128, multiChannel: false }, zoomLevels: [128], keyboard: true }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log('Peaks instance ready'); var zoomview = peaksInstance.views.getView('zoomview'); var zoomLevels = [5, 10, 20, 30, 60, 120, 180, 'auto']; zoomview.setZoom({ seconds: zoomLevels[0] }); var zoom = document.getElementById('zoom'); for (var i = 0; i < zoomLevels.length; i++) { var text = zoomLevels[i] === 'auto' ? 'Fit width' : (zoomLevels[i] + " seconds"); zoom.options[i] = new Option(text, i); } zoom.addEventListener('change', function(event) { var zoomLevel = zoomLevels[event.target.value]; zoomview.setZoom({ seconds: zoomLevel }); }); document.querySelector('button[data-action="seek"]').addEventListener('click', function(event) { var time = document.getElementById('seek-time').value; var seconds = parseFloat(time); if (!Number.isNaN(seconds)) { peaksInstance.player.seek(seconds); } }); var amplitudeScales = { "0": 0.0, "1": 0.1, "2": 0.25, "3": 0.5, "4": 0.75, "5": 1.0, "6": 1.5, "7": 2.0, "8": 3.0, "9": 4.0, "10": 5.0 }; document.getElementById('amplitude-scale').addEventListener('input', function(event) { var scale = amplitudeScales[event.target.value]; var view = peaksInstance.views.getView(); view.setAmplitudeScale(scale); }); document.getElementById('waveform-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setWaveformColor(event.target.value); }); document.getElementById('played-waveform-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setPlayedWaveformColor(event.target.value); }); document.getElementById('axis-label-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setAxisLabelColor(event.target.value); }); document.getElementById('axis-gridline-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setAxisGridlineColor(event.target.value); }); document.querySelector('button[data-action="set-start-time"]').addEventListener('click', function(event) { var time = document.getElementById('start-time').value; var seconds = parseFloat(time); if (!Number.isNaN(seconds)) { var view = peaksInstance.views.getView(); view.setStartTime(seconds); } }); // Zoomview waveform events peaksInstance.on('zoomview.update', function(event) { console.log('zoomview.update:', event); }); }); })(peaks); ``` -------------------------------- ### Initialize Peaks.js with Script Tag Source: https://github.com/bbc/peaks.js/blob/master/README.md Include Peaks.js via a script tag and initialize it with options. Ensure the DOM elements for zoomview, overview, and media are available. ```html ``` -------------------------------- ### Initialize Peaks.js with Options Source: https://github.com/bbc/peaks.js/blob/master/demo/overview-waveform.html Use this snippet to initialize Peaks.js with specific configuration options for a single waveform view. It requires an audio element and data URIs for waveform data. Event listeners are set up for user interactions. ```javascript (function(Peaks) { var options = { overview: { container: document.getElementById('overview-container'), waveformColor: '#cccccc', playedWaveformColor: '#888888', showPlayheadTime: true }, mediaElement: document.getElementById('audio'), dataUri: { arraybuffer: '/TOL\_6min\_720p\_download.dat', json: '/TOL\_6min\_720p\_download.json' }, keyboard: true }; Peaks.init(options, function(err, peaksInstance) { if (err) { console.error(err.message); return; } console.log('Peaks instance ready'); document.querySelector('button\[data-action="seek"\ ]').addEventListener('click', function(event) { var time = document.getElementById('seek-time').value; var seconds = parseFloat(time); if (!Number.isNaN(seconds)) { peaksInstance.player.seek(seconds); } }); var amplitudeScales = { "0": 0.0, "1": 0.1, "2": 0.25, "3": 0.5, "4": 0.75, "5": 1.0, "6": 1.5, "7": 2.0, "8": 3.0, "9": 4.0, "10": 5.0 }; document.getElementById('amplitude-scale').addEventListener('input', function(event) { var scale = amplitudeScales[event.target.value]; var view = peaksInstance.views.getView(); view.setAmplitudeScale(scale); }); document.getElementById('waveform-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setWaveformColor(event.target.value); }); document.getElementById('played-waveform-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setPlayedWaveformColor(event.target.value); }); document.getElementById('axis-label-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setAxisLabelColor(event.target.value); }); document.getElementById('axis-gridline-color').addEventListener('input', function(event) { var view = peaksInstance.views.getView(); view.setAxisGridlineColor(event.target.value); }); }); })(peaks); ``` -------------------------------- ### Get Current Playback Time Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Returns the current playback time of the associated media element in seconds. ```javascript const time = instance.player.getCurrentTime(); ``` -------------------------------- ### player.playing Source: https://github.com/bbc/peaks.js/blob/master/doc/API.md Emitted when media playback is started or restarted after being paused. The event handler receives the current playback time. ```APIDOC ## player.playing ### Description This event is emitted when media playback is started or restarted after being paused. This event is equivalent to the [HTMLMediaElement playing event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playing_event). The event handler receives current playback time. ### Code Example ```js instance.on('player.playing', function(time) { console.log(`Playing at ${time} seconds`); }); ``` ```