UNPKG

@vueuse/sound

Version:

🔊 A Vue composable for playing sound effects

98 lines (94 loc) • 2.58 kB
'use strict'; const vueDemi = require('vue-demi'); function useSound(url, { volume = 1, playbackRate = 1, soundEnabled = true, interrupt = false, autoplay = false, onload, ...delegated } = {}) { const HowlConstructor = vueDemi.ref(null); const isPlaying = vueDemi.ref(false); const duration = vueDemi.ref(null); const sound = vueDemi.ref(null); function handleLoad(soundId) { if (typeof onload === "function") onload.call(this, soundId); duration.value = (duration.value || sound.value?.duration() || 0) * 1e3; if (autoplay === true) { isPlaying.value = true; } } vueDemi.onMounted(async () => { await import('howler'); HowlConstructor.value = Howl; sound.value = new HowlConstructor.value({ src: vueDemi.unref(url), volume: vueDemi.unref(volume), rate: vueDemi.unref(playbackRate), onload: handleLoad, ...delegated }); }); vueDemi.watch( () => [vueDemi.unref(url)], () => { if (HowlConstructor.value && HowlConstructor.value && sound && sound.value) { sound.value = new HowlConstructor.value({ src: vueDemi.unref(url), volume: vueDemi.unref(volume), rate: vueDemi.unref(playbackRate), onload: handleLoad, ...delegated }); } } ); vueDemi.watch( () => [vueDemi.unref(volume), vueDemi.unref(playbackRate)], () => { if (sound.value) { sound.value.volume(vueDemi.unref(volume)); sound.value.rate(vueDemi.unref(playbackRate)); } } ); const play = (options) => { if (typeof options === "undefined") { options = {}; } if (!sound.value || !soundEnabled && !options.forceSoundEnabled) { return; } if (interrupt) { sound.value.stop(); } if (options.playbackRate) { sound.value.rate(options.playbackRate); } sound.value.play(options.id); sound.value.once("end", () => { if (sound.value && sound.value && !sound.value.playing()) { isPlaying.value = false; } }); isPlaying.value = true; }; const stop = (id) => { if (!sound.value) { return; } sound.value.stop(typeof id === "number" ? id : void 0); isPlaying.value = false; }; const pause = (id) => { if (!sound.value) { return; } sound.value.pause(typeof id === "number" ? id : void 0); isPlaying.value = false; }; const returnedValue = { play, sound, isPlaying, duration, pause, stop }; return returnedValue; } exports.useSound = useSound;