51 lines
1.1 KiB
TypeScript
51 lines
1.1 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo } from "react";
|
|
|
|
export const useAudio = () => {
|
|
const audio = useMemo(() => {
|
|
if (typeof window !== "undefined") {
|
|
const audioElement = new Audio("/audio/notification-new-message-1.wav");
|
|
audioElement.preload = "auto";
|
|
return audioElement;
|
|
}
|
|
return null;
|
|
}, []);
|
|
|
|
const _audioContext = useMemo(() => {
|
|
if (typeof window !== "undefined") {
|
|
return new (window.AudioContext || window.webkitAudioContext)();
|
|
}
|
|
return null;
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!audio) return;
|
|
|
|
const handleClick = () => {
|
|
audio.currentTime = 0;
|
|
audio.play();
|
|
setTimeout(() => {
|
|
audio.pause();
|
|
}, 10);
|
|
};
|
|
document.addEventListener("click", handleClick, { once: true });
|
|
return () => {
|
|
document.removeEventListener("click", handleClick);
|
|
};
|
|
}, [audio]);
|
|
|
|
const playNewMessageNotification = useCallback(() => {
|
|
if (!audio) return;
|
|
audio.currentTime = 0;
|
|
audio.play();
|
|
}, [audio]);
|
|
|
|
return useMemo(
|
|
() => ({
|
|
playNewMessageNotification,
|
|
}),
|
|
[playNewMessageNotification]
|
|
);
|
|
};
|