Advertisement
Guest User

React Typescript AudioPlayer component

a guest
Jul 8th, 2024
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.05 KB | Source Code | 0 0
  1. import React, { useRef, useEffect } from "react";
  2.  
  3. interface AudioPlayerProps {
  4.   play?: boolean;
  5.   src: string;
  6.   triggerCounter?: number;
  7.   onFinish?: () => void;
  8. }
  9.  
  10. export const AudioPlayer = ({ play = false, src, onFinish, triggerCounter = 0 }: AudioPlayerProps) => {
  11.   const audioRef = useRef<HTMLAudioElement | null>(null);
  12.  
  13.   useEffect(() => {
  14.     if (play) {
  15.       playAudio();
  16.     }
  17.   }, [play]);
  18.  
  19.   useEffect(() => {
  20.     if (triggerCounter > 0) {
  21.       playAudio();
  22.     }
  23.   }, [triggerCounter]);
  24.  
  25.   const playAudio = (): void => {
  26.     if (audioRef.current) {
  27.       void audioRef.current.play();
  28.     }
  29.   };
  30.  
  31.   const handleAudioEnded = (): void => {
  32.     if (onFinish) {
  33.       onFinish();
  34.     }
  35.   };
  36.  
  37.   return (
  38.     <div>
  39.       {/* eslint-disable-next-line jsx-a11y/media-has-caption -- sound effect */}
  40.       <audio ref={audioRef} controls className="hidden" onEnded={handleAudioEnded}>
  41.         <source src={src} type="audio/mp3" />
  42.         Your browser does not support the audio element.
  43.       </audio>
  44.     </div>
  45.   );
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement