I am trying to add and remove an audio track from a stream. The removeTrack function works but the addTrack function throws the error below when it is called
Uncaught TypeError: Failed to execute 'addTrack' on 'MediaStream': parameter 1 is not of type 'MediaStreamTrack'.
at addAudio (video.jsx:22)
at HTMLButtonElement.document.querySelector.onclick (video.jsx:32)
Below Is My Code
componentDidMount = () => {
var Mstream;
const video = document.querySelector("video")
const hasMedia = () => {
return navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia
}
const fetchMedia = () => {
var constraints = { video: true, audio: true }
navigator.getUserMedia(constraints, (stream) => {
Mstream = stream
video.srcObject = stream
}, (error) => { })
}
const addAudio = () => {
console.log("Adding")
const audioTracks = Mstream.getAudioTracks()
Mstream.addTrack(audioTracks[0])
console.log('Added')
}
const removeAudio = () => {
console.log('removing')
const audioTracks = Mstream.getAudioTracks()
Mstream.removeTrack(audioTracks[0])
console.log('Removed')
}
document.querySelector("button#add").onclick = () => addAudio()
document.querySelector("button#remove").onclick = () => removeAudio()
hasMedia() && fetchMedia()
}
But it still returns the same error with the addTrack function
const addAudio = () => {
console.log("Adding")
const audioTracks = Mstream.getAudioTracks()
if(audioTracks.length <= 0){
Mstream.addTrack(audioTracks[0])
console.log("Track Added")
}
else{
console.log("Cannot Add Track")
}
}
const removeAudio = () => {
console.log('removing')
const audioTracks = Mstream.getAudioTracks()
if (audioTracks.length > 0) {
Mstream.removeTrack(audioTracks[0])
}
else {
console.log("Cannot Remove It")
}
}
The MediaStream.getAudioTracks() method returns an array of MediaStreamTrack objects. But, it provides no guarantee that there are any elements in the array. audioTracks[0] may be undefined, which would cause this error to occur.
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