@vueuse/sound
Version:
🔊 A Vue composable for playing sound effects
96 lines (93 loc) • 2.44 kB
JavaScript
import { ref, onMounted, unref, watch } from 'vue-demi';
function useSound(url, { volume = 1, playbackRate = 1, soundEnabled = true, interrupt = false, autoplay = false, onload, ...delegated } = {}) {
const HowlConstructor = ref(null);
const isPlaying = ref(false);
const duration = ref(null);
const sound = 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;
}
}
onMounted(async () => {
await import('howler');
HowlConstructor.value = Howl;
sound.value = new HowlConstructor.value({
src: unref(url),
volume: unref(volume),
rate: unref(playbackRate),
onload: handleLoad,
...delegated
});
});
watch(
() => [unref(url)],
() => {
if (HowlConstructor.value && HowlConstructor.value && sound && sound.value) {
sound.value = new HowlConstructor.value({
src: unref(url),
volume: unref(volume),
rate: unref(playbackRate),
onload: handleLoad,
...delegated
});
}
}
);
watch(
() => [unref(volume), unref(playbackRate)],
() => {
if (sound.value) {
sound.value.volume(unref(volume));
sound.value.rate(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;
}
export { useSound };