Hello i want to make a button that mutes and unmutes sound in html5 tag.
Here what i have so far. Sadly it doesnt work

.ts

soundOnOff()
{
    let audio = document.getElementById('muteSound') as HTMLMediaElement
    audio.muted = true;
}

html

               <button onclick="enableMute()" type="button">Mute sound</button>
<video id="muteSound" muted="true" playsinline autoplay loop preload="auto">
    <source src="assets/videos/louvre.mp4" type="video/mp4" >
</video>

Dani AI

Generated

Good start, . Two things are biting you: your TS function only ever mutes (never unmutes), as noted, and your button calls a different function name than the one in your TS. On mobile, browsers allow unmuting only in direct response to a user gesture, so wire a handler to the button and toggle the media element’s muted property. Also be sure the code runs after the DOM is ready.

// TypeScript
document.addEventListener('DOMContentLoaded', () => {
  const video = document.querySelector('#muteSound') as HTMLVideoElement | null;
  const btn = document.querySelector('#muteToggle') as HTMLButtonElement | null;
  if (!video || !btn) return;

  // Keep autoplay reliable on mobile: start muted.
  video.muted = true;

  const updateUI = () => {
    btn.textContent = video.muted ? 'Unmute' : 'Mute';
    btn.setAttribute('aria-pressed', String(!video.muted));
  };

  btn.addEventListener('click', () => {
    video.muted = !video.muted;
    // If the volume was 0, give it a sensible value when unmuting.
    if (!video.muted && video.volume === 0) video.volume = 1.0;
    updateUI();
  });

  updateUI();
});

How to use it: give your button an id like muteToggle and remove the inline onclick. Rely on the property, not the HTML attribute: video.muted reflects the live state, while the muted attribute only sets the initial state. If you prefer inline handlers, make sure the function name matches and is on window so the HTML can see it. For mobile: a user gesture is required to unmute; click works, and pointerup can help if you run into device quirks. As suggested, implement the on/off function and report back with any console errors if it still refuses to toggle.

Recommended Answers

All 3 Replies

In your .ts script, where do you toggle audio.muted? I only see code to set it to true. Where is false?

Also, if your script language support it the line of code could be audio.muted = not(audio.muted)
https://html.com/attributes/audio-muted/ shows the mini-player with the audio mute control showing without any added code.

The sound plays in autoplay when the page loads and i need a on/off button. I haven't created a on/off function

commented: Check out the link. I see a button in the control to mute/unmute. +15

Try to create thу on/off function and describe the results.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.