Adjusting the audio length in React/Typescript: A simple guide

I'm currently developing a web app with React and TypeScript. One of the components I created is called SoundEffect, which plays an mp3 file based on the type of sound passed as a prop.

interface ISoundEffectProps {
    soundType: string,
    // duration?: number, <- want to add this
}

const SoundEffect: React.FunctionComponent<ISoundEffectProps> = (props) => {
  const sound = soundSelector(props.soundType)
  return (
    <div>
        <audio src={sound} autoPlay></audio>
    </div>
  );
};

export default SoundEffect;

The function soundSelector() retrieves the corresponding mp3 file based on the soundType. I now wish to incorporate a duration feature so that when the component is rendered like this:

<SoundEffect soundType="count-down" duration=3000/>

the sound only plays for 3 seconds before stopping. Currently, I have to create separate mp3 files with different durations, which feels unnecessary. Since buttons cannot be added to this component, I'm unsure if a function-triggering component can be used (please correct me if I'm wrong). If anyone has a solution or knows of libraries/packages that could help resolve this issue, kindly provide assistance. Thank you!

------I'll detail a solution below------

interface ISoundEffectProps {
  id: string,
  soundType: string,
  duration?: number,
}

const SoundEffect: React.FunctionComponent<ISoundEffectProps> = (props) => {
  const sound = soundSelector(props.soundType); // "../assets/sounds/example.mp3"
  const audio = document.getElementById(props.id) as HTMLAudioElement; 
// without "as HTMLAudioElement", audio becomes HTMLElement, which does not have pause() method. 

  function startTimer(duration: number) {
    if (audio != null) { // <- audio.pause() creates uncaught typeerror when audio is null
      const interval = setInterval(() => {
        audio.pause();
      }, duration 1000);
    }
  }
  return (
    <div>
        <audio autoPlay id={props.id} onPlay={()=> startTimer(props.duration || 10)}>
          <source src={sound} type="audio/mp3"/>
        </audio>
    </div>
  );
}

Now, I can use this component as follows:

<SoundEffect id="beep_id", soundType="beep", duration={5}/>

This component will stop playing the sound after 5 seconds. Similarly, setting duration={10} would cause it to stop after 10 seconds.

Answer №1

One way to pause the playback at a certain point is by utilizing the set interval function.

function startTimer(duration) {
 const timer = setInterval(() => {
     audioReference.pause()
    }, duration * 1000);
}
...

<audio src={soundFile} autoPlay onplay={() => startTimer(playbackDuration)}></audio>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capture and set the new value of the Datetime picker in MUI upon user's acceptance click

import React from 'react' import { Stack, Typography } from '@mui/material' import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker' import { renderTimeViewClock } from '@mui/x-date-pickers/timeViewRenderers&ap ...

Is the useNavigate() function failing to work consistently?

Currently facing an issue while working on a MERN Web App. When logging in with an existing account, the backend API call returns user properties and a JWT Token. Upon saving it, I use the navigate function to redirect the User to the homepage. Everything ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Transitioning to webpack 5: Encountering an error - Unable to access the 'prototype' property of an undefined value

After spending several days attempting to fix this bug, none of the solutions I found online have been helpful. The issue arose after migrating from webpack version 4 to version 5. Here is the specific error that's occurring: https://i.stack.imgur.co ...

Issue with calling a function in Material UI (React.js) not being executed

Today, I started working with Material UI but can't figure out why the function handelSubmit() is not being called. There is no output printed on the console and the function seems to be inactive. I'm unsure where I've made an error. Tha ...

Saving a boolean value and a number to Firestore in an Angular application

In my Angular 5 typescript project, I have a form with various input fields and selections. Here is how I am capturing the form values: let locked: boolean = (<HTMLInputElement>document.getElementById("locked")).value; let maxPlayers: number = (& ...

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

Invoking a method in a derived class upon completion of asynchronous logic within the base class

Currently, I am in the process of building an Angular application. One aspect of my project involves a class that extends a base class. While this approach may not be ideal, I am curious to know what would be the best practice for BaseClass to trigger me ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Issue encountered: Material-UI menu remains open even when a dialog is active

Currently, I am utilizing react along with material-ui. In my JSX file, I have created a dialog component as follows: export default class CartoviewAbout extends React.Component { constructor(props) { super(props); this. ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...

Unique bullets for page navigation in Swiper.js/react

I've been attempting to implement custom paginations for my component in order to have bullets outside the container, but unfortunately they are not showing up in the DOM. Below is the code snippet of the component: export function CommentSlider({ co ...

React fails to display image on the server

One issue I'm facing with my React project on the server is that some images are not being displayed. Click here to view image description The console error message reads: ASGimagen.png:1 GET https://[url of my server]/autodiagnostico/cuadroanimado ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Discussing the size of windows within React Material-UI's makeStyles framework

When I create a custom style for a specific component, my const declaration typically looks like this: const useStyles = makeStyles((theme: Theme) => createStyles({ screen: { margin: 0, padding: 0 }, surface: { backgroun ...

The type of the object is classified as 'unknown' (2571) while utilizing the map() function with an array containing objects

After researching this error extensively on Google and reading multiple posts, I am still unable to find a solution. I am trying to fetch data from an external API call that has the following signature: const properties: { [x: string]: unknown;} | { [x: s ...

Unexpected date format displayed by the flat picker calendar

The expected date format is "DD-MM-YYYY" but the shown date format in the UI is "YYYY-MM-DD". Click here to view the UI image Initially, before opening the date picker, the date is displayed in the expected format as "DD-MM-YYYY". Upon opening the date p ...