UNPKG

js-tts-wrapper

Version:

A JavaScript/TypeScript library that provides a unified API for working with multiple cloud-based Text-to-Speech (TTS) services

87 lines (86 loc) 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AudioPlayback = void 0; /** * Utility class for audio playback */ class AudioPlayback { constructor() { Object.defineProperty(this, "audioElement", { enumerable: true, configurable: true, writable: true, value: null }); } /** * Play audio from a URL * @param url URL of the audio to play * @param onStart Callback when playback starts * @param onEnd Callback when playback ends * @returns Promise that resolves when playback starts */ play(url, onStart, onEnd) { return new Promise((resolve) => { this.stop(); this.audioElement = new Audio(url); this.audioElement.onplay = () => { if (onStart) onStart(); resolve(); }; this.audioElement.onended = () => { if (onEnd) onEnd(); }; this.audioElement.play(); }); } /** * Play audio from a Blob * @param blob Audio blob * @param onStart Callback when playback starts * @param onEnd Callback when playback ends * @returns Promise that resolves when playback starts */ playFromBlob(blob, onStart, onEnd) { const url = URL.createObjectURL(blob); return this.play(url, onStart, onEnd).then(() => { // Clean up the URL when playback ends if (this.audioElement) { this.audioElement.onended = () => { if (onEnd) onEnd(); URL.revokeObjectURL(url); }; } }); } /** * Pause audio playback */ pause() { if (this.audioElement) { this.audioElement.pause(); } } /** * Resume audio playback */ resume() { if (this.audioElement) { this.audioElement.play(); } } /** * Stop audio playback */ stop() { if (this.audioElement) { this.audioElement.pause(); this.audioElement.currentTime = 0; this.audioElement = null; } } } exports.AudioPlayback = AudioPlayback;