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
There are a couple of issues here.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With