PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] How to update the mute property of DOM Audio realtime

 August 13, 2022     dom, javascript, next.js, reactjs     No comments   

Issue

I need some help on how I can update the DOM audio in real time.

I'm trying to make the audio muted and unmuted based on the user preference,

The recording is saved in the public folder.

The audio is working fine on the first load if you set mute to be true or false, then when you try to change it, the mute props do not update.

Here is a short sample of my code, I'm using next.js.

import { RECORDING } from '@/constants/media.constant';
import { useEffect, useState } from 'react';

function Sample() {
  const [mute, setMute] = useState(false);

  useEffect(() => {
    (() => playWithAudio())();
  }, []);

  const playWithAudio = () => {
    const tryToPlay = setInterval(() => {
      // audio recording, format mp3
      const audio = new Audio(RECORDING.HELLO);
      audio.loop = true;
      audio.muted = mute;

      audio
        .play()
        .then(() => {
          clearInterval(tryToPlay);
        })
        .catch(() => console.info('User has not interacted with DOM yet.'));
    }, 1000);
  };

  return (
    <>
      <button onClick={() => setMute(!mute)}>Click</button>
    </>
  );
}

export default Sample;

Any help would be appreciated.


Solution

Give this a try

import { useEffect, useState } from "react";
import { RECORDING } from "@/constants/media.constant";

function Sample() {
  const [mute, setMute] = useState(false);
  const [audio, setAudio] = useState(null);

  useEffect(() => {
    setAudio(new Audio(RECORDING.HELLO));
  }, []);

  useEffect(() => {
    if (audio) playWithAudio();
  }, [audio]);

  const playWithAudio = () => {
    const tryToPlay = setInterval(() => {
      // audio recording, format mp3
      audio.loop = true;
      audio.muted = mute;
   

      audio
        .play()
        .then(() => {
          clearInterval(tryToPlay);
        })
        .catch(() => console.info("User has not interacted with DOM yet."));
    }, 1000);
  };

  return (
    <>
      <button
        onClick={() => {
          if (audio) audio.muted = !mute;
          setMute(!mute);
        }}
      >
        {mute ? "UnMute" : "Mute"}
      </button>
    </>
  );
}

export default Sample;



Answered By - Inder
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing