Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useRef, useEffect } from "react";
- interface AudioPlayerProps {
- play?: boolean;
- src: string;
- triggerCounter?: number;
- onFinish?: () => void;
- }
- export const AudioPlayer = ({ play = false, src, onFinish, triggerCounter = 0 }: AudioPlayerProps) => {
- const audioRef = useRef<HTMLAudioElement | null>(null);
- useEffect(() => {
- if (play) {
- playAudio();
- }
- }, [play]);
- useEffect(() => {
- if (triggerCounter > 0) {
- playAudio();
- }
- }, [triggerCounter]);
- const playAudio = (): void => {
- if (audioRef.current) {
- void audioRef.current.play();
- }
- };
- const handleAudioEnded = (): void => {
- if (onFinish) {
- onFinish();
- }
- };
- return (
- <div>
- {/* eslint-disable-next-line jsx-a11y/media-has-caption -- sound effect */}
- <audio ref={audioRef} controls className="hidden" onEnded={handleAudioEnded}>
- <source src={src} type="audio/mp3" />
- Your browser does not support the audio element.
- </audio>
- </div>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement