|
| 1 | +/* |
| 2 | + * Copyright 2024 Comcast Cable Communications Management, LLC |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + * |
| 15 | + * SPDX-License-Identifier: Apache-2.0 |
| 16 | + */ |
| 17 | + |
| 18 | +import { Log } from '../lib/log.js' |
| 19 | + |
| 20 | +export default { |
| 21 | + name: 'audio', |
| 22 | + plugin(options = {}) { |
| 23 | + let audioContext = undefined |
| 24 | + let audioEnabled = true |
| 25 | + let activeTracks = {} // Store all active track controllers |
| 26 | + |
| 27 | + try { |
| 28 | + audioContext = new AudioContext() |
| 29 | + } catch (e) { |
| 30 | + Log.error('AudioContext is not supported or failed to initialize. Audio will be disabled.') |
| 31 | + audioEnabled = false |
| 32 | + } |
| 33 | + |
| 34 | + let tracks = {} |
| 35 | + |
| 36 | + const loadAudioData = async (url) => { |
| 37 | + if (audioEnabled === false) return |
| 38 | + try { |
| 39 | + const response = await fetch(url) |
| 40 | + |
| 41 | + if (!response.ok) { |
| 42 | + throw Error(`${response.status} - ${response.statusText}`) |
| 43 | + } |
| 44 | + |
| 45 | + const arrayBuffer = await response.arrayBuffer() |
| 46 | + return audioContext.decodeAudioData(arrayBuffer) |
| 47 | + } catch (e) { |
| 48 | + Log.error(`Failed to load audio from ${url}: ${e}`) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + const preloadTracks = async (trackList) => { |
| 53 | + if (audioEnabled === false) return |
| 54 | + for (const [key, url] of Object.entries(trackList)) { |
| 55 | + const audioData = await loadAudioData(url) |
| 56 | + if (audioData) { |
| 57 | + tracks[key] = audioData |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + const createTrackController = (source, gainNode, trackId) => { |
| 63 | + return { |
| 64 | + stop() { |
| 65 | + try { |
| 66 | + source.stop() |
| 67 | + } catch (e) { |
| 68 | + Log.warn('Error stopping audio track', trackId) |
| 69 | + } |
| 70 | + |
| 71 | + delete activeTracks[trackId] |
| 72 | + }, |
| 73 | + setVolume(volume) { |
| 74 | + gainNode.gain.value = volume |
| 75 | + }, |
| 76 | + get source() { |
| 77 | + return source |
| 78 | + }, |
| 79 | + get gainNode() { |
| 80 | + return gainNode |
| 81 | + }, |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + const playAudioBuffer = (buffer, trackId, { volume = 1, pitch = 1 } = {}) => { |
| 86 | + if (audioEnabled === false || audioContext === undefined) { |
| 87 | + Log.warn('AudioContext not available. Cannot play audio.') |
| 88 | + return |
| 89 | + } |
| 90 | + |
| 91 | + const source = audioContext.createBufferSource() |
| 92 | + source.buffer = buffer |
| 93 | + source.playbackRate.value = pitch |
| 94 | + |
| 95 | + const gainNode = audioContext.createGain() |
| 96 | + gainNode.gain.value = volume |
| 97 | + |
| 98 | + source.connect(gainNode) |
| 99 | + gainNode.connect(audioContext.destination) |
| 100 | + |
| 101 | + source.onended = () => { |
| 102 | + delete activeTracks[trackId] |
| 103 | + Log.info(`Track ${trackId} finished playing.`) |
| 104 | + } |
| 105 | + |
| 106 | + // Create and store the track controller |
| 107 | + const trackController = createTrackController(source, gainNode, trackId) |
| 108 | + activeTracks[trackId] = trackController |
| 109 | + |
| 110 | + source.start() |
| 111 | + |
| 112 | + return trackController |
| 113 | + } |
| 114 | + |
| 115 | + const playTrack = (key, options = {}, trackId = key) => { |
| 116 | + if (audioEnabled === false) { |
| 117 | + Log.warn('AudioContext not available. Cannot play track.') |
| 118 | + return |
| 119 | + } |
| 120 | + if (tracks[key] !== undefined) { |
| 121 | + return playAudioBuffer(tracks[key], trackId, options) |
| 122 | + } else { |
| 123 | + Log.warn(`Track ${key} not found in the library.`) |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + const playUrl = async (url, options = {}, trackId = url) => { |
| 128 | + if (audioEnabled === false) return |
| 129 | + const audioData = await loadAudioData(url) |
| 130 | + if (audioData !== undefined) { |
| 131 | + return playAudioBuffer(audioData, trackId, options) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + const stop = (trackId) => { |
| 136 | + if (audioEnabled === false || activeTracks[trackId] === undefined) return |
| 137 | + activeTracks[trackId].stop() |
| 138 | + } |
| 139 | + |
| 140 | + const stopAll = () => { |
| 141 | + if (audioEnabled === false) return |
| 142 | + while (Object.keys(activeTracks).length > 0) { |
| 143 | + const trackId = Object.keys(activeTracks)[0] |
| 144 | + stop(trackId) |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + const removeTrack = (key) => { |
| 149 | + if (tracks[key] !== undefined) { |
| 150 | + // stop if the track happens to be active as well |
| 151 | + if (activeTracks[key] !== undefined) { |
| 152 | + activeTracks[key].stop() |
| 153 | + } |
| 154 | + |
| 155 | + delete tracks[key] |
| 156 | + Log.info(`Track ${key} removed from the preloaded library.`) |
| 157 | + } else { |
| 158 | + Log.warn(`Track ${key} not found in the library.`) |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + const destroy = () => { |
| 163 | + if (audioEnabled === false) return |
| 164 | + stopAll() // Stop all active tracks before destroying |
| 165 | + audioContext.close() |
| 166 | + } |
| 167 | + |
| 168 | + if (options.preload === true && audioEnabled === true) { |
| 169 | + preloadTracks(options.preload) |
| 170 | + } |
| 171 | + |
| 172 | + // Public API for the Audio Plugin |
| 173 | + return { |
| 174 | + get audioEnabled() { |
| 175 | + return audioEnabled |
| 176 | + }, |
| 177 | + get activeTracks() { |
| 178 | + return activeTracks |
| 179 | + }, |
| 180 | + get tracks() { |
| 181 | + return tracks |
| 182 | + }, |
| 183 | + get state() { |
| 184 | + return audioContext.state |
| 185 | + }, |
| 186 | + destroy, // Destroy the audio context and stop all tracks |
| 187 | + pause() { |
| 188 | + return audioContext.suspend() |
| 189 | + }, |
| 190 | + playTrack, // Play a preloaded track by its key and return the track controller |
| 191 | + playUrl, // Play a track directly from a URL and return the track controller |
| 192 | + preload: preloadTracks, // Preload a set of audio tracks |
| 193 | + resume() { |
| 194 | + return audioContext.resume() |
| 195 | + }, |
| 196 | + removeTrack, // Remove a track from the preloaded library |
| 197 | + stop, // Stop a specific track by its ID |
| 198 | + stopAll, // Stop all active tracks |
| 199 | + } |
| 200 | + }, |
| 201 | +} |
0 commit comments