Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Play Audio in React Typescript with play() function | Error: Property 'play' does not exist

I have created a simple Audio Player in React js with Typescript and I am trying to use the normal HTML5 functions to Play and Pause the Audio but it is not working.

When I do mytrack.play(); I get this error: Property 'play' does not exist on type 'HTMLElement'.

Here is my code:

import React, { Component } from "react";
import "./SimplePlayer.css";
import styled from "styled-components";

export interface SimplePlayerProps {}

var mytrack = document.getElementById("mytrack");
console.log(mytrack);
mytrack.play();

export class SimplePlayer extends Component<SimplePlayerProps> {
  constructor(props: SimplePlayerProps) {
    super(props);
    console.log(this.props);
    this.state = {};
  }

  render() {
    return (
      <div id="wrapper">
        <audio id="mytrack" controls>
          <source src="audio.mp3" />
        </audio>
        <nav>
          <div id="defaultBar">
            <div id="progressBar" />
          </div>
          <div id="buttons">
            <button type="button" id="playButton" />
            <button type="button" id="muteButton" />
            <span id="currentTime">0:00</span>/
            <span id="fullDuration">0:00</span>
          </div>
        </nav>
      </div>
    );
  }
}

Any Help would be really appreciated :) Many Thanks

Best Regards, Musayyab Naveed

like image 364
Musayyab Naveed Avatar asked Sep 12 '25 03:09

Musayyab Naveed


1 Answers

There are a couple of issues here.

  1. The play method exists on HTMLAudioElement and not HTMLElement. getElementById returns HTMLElement | null, so you'd have to cast mytrack as HTMLAudioElement for TypeScript to allow it.

But that's not the main problem.

  1. The real issue is that your code to get and play the audio file is running before the code (in render) that creates the audio element. If you're wanting to play the audio file immediately, try including the autoplay property on the audio element.
like image 62
Tyler Massey Avatar answered Sep 14 '25 17:09

Tyler Massey