Reputation: 457
I am trying to follow a basic Web Audio API tutorial from MDN, except I'm using TypesScript and React (made with create-react-app) instead of vanilla JS. Since I'm in React, I'm using the useRef hook to reference the audio element in my jsx, instead of document.querySelector() like in the tutorial. Here is the problematic code:
const audioContext = new AudioContext();
const audioRef = useRef<HTMLMediaElement>(null);
const track = audioContext.createMediaElementSource(audioRef.current);
Gives a TS error under audioRef.current that
Argument of type 'HTMLMediaElement | null' is not assignable to parameter of type 'HTMLMediaElement'.
I tried casting audioRef.current as an HTMLMediaElement like this:
const track = audioContext.createMediaElementSource(audioRef.current as HTMLMediaElement);
This gets rid of the error in my editor, but then the code fails in the browser; this is the error I get there:
TypeError: Failed to execute 'createMediaElementSource' on 'AudioContext': parameter 1 is not of type 'HTMLMediaElement'.
I also tried defining the audioRef variable as an HTMLAudioElement instead of an HTMLMediaElement like so: const audioRef = useRef<HTMLAudioElement>(null);
but that doesn't fix anything.
I should also note that I tried this in a plain TS file and get the same errors there. So I don't think the problem is related to use of the useRef hook.
Is there someway to get this to work? I'm worried that the Type definitions just aren't matching up with the functionality of the Web Audio API.
Upvotes: 0
Views: 1260
Reputation: 457
I realized the problem: createMediaElementSource was being called with audioRef.current which was null at the time of execution. Whoops.
Upvotes: 1