Audio in React – display current time - createIT
Get a free advice now!

    Pick the topic
    Developer OutsourcingWeb developingApp developingDigital MarketingeCommerce systemseEntertainment systems

    Thank you for your message. It has been sent.
    Tags

    Audio in React – display current time

    Audio in React – display current time

    CHALLENGE: get current audio duration time and display

    SOLUTION: use the onTimeUpdate event

    Having an audio file played, we would like to have the ability to know the current play time. In React, this can be achieved by using the onTimeUpdate event. Knowing currentTime, we need to parse the value and format it using the str_pad_left function. This technique can also be used for streaming audio/video.

    The Ontimeupdate event is triggered when the playing position of the file changes. It’s executed every 200-250ms. The event is invoked by playing or moving playback position.

    OnTimeUpdate Demo

    In our Demo, we’re going to have 2 files embedded and displaying current play time, with live updating. The CurrentStreamTime component uses prop to set current time (updating the parent’s state from the child). We support both audio and video files. We use event.target.currentTime and concatenate minutes and seconds to properly format time.

    Demo with an animated film preview

    The main application file:

    // src/App.jsx
    import React, {useState, useEffect} from 'react';
    import './App.css';
    import {CurrentStreamTime} from "./CurrentStreamTime";
    function App() {
      const[currentTime1, setCurrentTime1] = useState('00:00');
      const[currentTime2, setCurrentTime2] = useState('00:00');
      return (
        <div className="App">
          <div className={'currentTime'}>
            <CurrentStreamTime src={'https://www.w3schools.com/html/mov_bbb.mp4'} type={'video'} setCurrentTime={setCurrentTime1} />
            <p>⏱ {currentTime1}</p>
          </div>
          <div className={'currentTime'}>
            <CurrentStreamTime src={'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_5MG.mp3'} type={'audio'} setCurrentTime={setCurrentTime2} />
            <p>⏱ {currentTime2}</p>
          </div>
        </div>
      );
    }
    export default App;

    The file with the main component and the onTimeUpdate event handler:

    // src/CurrentStreamTime.jsx
    import React from 'react';
    export const CurrentStreamTime = (props) => {
        const {src, type='audio', setCurrentTime} = props;
        const timeUpdate = (event) => {
            const minutes = Math.floor(event.target.currentTime / 60);
            const seconds = Math.floor(event.target.currentTime - minutes * 60);
            const currentTime = str_pad_left(minutes,'0',2) + ':' + str_pad_left(seconds,'0',2);
            setCurrentTime(currentTime);
        }
        const str_pad_left = (string,pad,length) => {
            return (new Array(length+1).join(pad)+string).slice(-length);
        }
        let htmlTag = '';
        if(type === 'audio') {
            htmlTag = <audio src={src} autoPlay muted controls onTimeUpdate={timeUpdate} />;
        }
        if(type === 'video') {
            htmlTag = <video src={src} autoPlay muted controls loop onTimeUpdate={(event) => {timeUpdate(event)} } />;
        }
        return (
            <>
                {htmlTag}
            </>
        );
    }

    Additional CSS styles:

    body {
      background:#000;
    }
    .App {
      text-align: center;
      max-width:700px;
      margin:15px auto;
      background:#999;
      display:flex;
      justify-content: center;
      align-items: center;
    }
    .currentTime {
      border:10px solid transparent;
    }
    .currentTime p {
      display:inline-block;
      background:#fff;
      padding:7px 14px;
      border-radius:5px;
      font-weight:bold;
      color:#333;
    }
    Animated preview of the player

    Source code

    Here is the published source code: https://github.com/createit-dev/107-audio-in-react-display-current-time
    To run it:
    1) Clone the repo
    2) npm install
    3) npm start

    That’s all for today. Follow us for more useful tips and guidelines.

    Do you need someone to implement this React time solution for you? Check out our custom web application development page or our specialists for hire in the outsourcing section.

    Comments
    0 response

    Add comment

    Your email address will not be published. Required fields are marked *

    Popular news

    Fetching Time records from ActiveCollab API
    • Dev Tips and Tricks

    Fetching Time records from ActiveCollab API

    September 9, 2024 by createIT
    Docker Compose for PrestaShop
    • Dev Tips and Tricks

    Docker Compose for PrestaShop

    September 2, 2024 by createIT
    WordPress wizard in admin – step by step
    • Dev Tips and Tricks

    WordPress wizard in admin – step by step

    August 29, 2024 by createIT
    Order Status Sync between PrestaShop and External APIs
    • Dev Tips and Tricks

    Order Status Sync between PrestaShop and External APIs

    August 26, 2024 by createIT
    What is PHP used for in web development 
    • Dev Tips and Tricks

    What is PHP used for in web development 

    August 22, 2024 by createIT
    Automating WooCommerce product availability date
    • Dev Tips and Tricks

    Automating WooCommerce product availability date

    August 15, 2024 by createIT
    WP Quiz Adventure – FAQ
    • Dev Tips and Tricks

    WP Quiz Adventure – FAQ

    August 12, 2024 by createIT
    Retrieval Augmented Generation tutorial and OpenAI example
    • Dev Tips and Tricks

    Retrieval Augmented Generation tutorial and OpenAI example

    August 8, 2024 by createIT
    10 useful SEO tools for the iGaming industry
    • Services
    • Technology

    10 useful SEO tools for the iGaming industry

    August 5, 2024 by createIT

    Support – Tips and Tricks
    All tips in one place, and the database keeps growing. Stay up to date and optimize your work!

    Contact us