htmlreactjsaudiolive-streaminginternet-radio

Audio html tag for live radio


I need the audio player to be in real time.

Current problem: When I give the command audio.pause() and then audio.play() the player returns from where it left off and not live.

Can someone help me? I'm using react with vite.

Actual code:

import { useState } from "react";

import {
  FaPlay,
  FaStop,
  FaVolumeUp,
  FaVolumeDown,
  FaVolumeOff,
  FaVolumeMute,
} from "react-icons/fa";

export function Player() {
  const [radioRunning, setRadioRunning] = useState(false);

  const playRadio = () => {
    const radio = document.getElementById("player") as HTMLAudioElement;
    radio.scrollTo()
    radioRunning ? radio.pause() : radio.play();
    setRadioRunning(!radioRunning);
  };
  return (
    <>
      <audio loop={false} id="player">
        <source
          src="<my-radio-stream-link>"
          type='audio/mp4; codecs="mp4a.40.5"'
        />
        <source
          src="<my-radio-stream-link>"
          type="audio/aacp"
        />
        <span>Your browser dont support that element.</span>
      </audio>
      <div className="w-full flex justify-center gap-8 fixed bottom-0 py-2 bg-zinc-800">
        <button className="p-2">
          <FaVolumeUp className="w-5 h-5 mx-auto" />
        </button>
        <button className="p-4 -translate-y-11 rounded-full" onClick={playRadio}>
          {radioRunning ? (
            <FaStop className="w-10 h-10" />
          ) : (
            <FaPlay className="w-10 h-10" />
          )}
        </button>
        <button className="p-2">
          <FaVolumeUp className="w-5 h-5 mx-auto" />
        </button>
      </div>
    </>
  );
}


Solution

  • Use your playRadio function is way to mute instead of stoping:

     const playRadio = () => {
        const radio = document.getElementById("player");
        radio.scrollTo()
    
        if(!radioRunning) radio.play()
        radio.muted = radioRunning;
    
        setRadioRunning(!radioRunning);
      };