play sound in javascript
snippet in html

play sound javascript

user7244

var audio = new Audio("folder_name/audio_file.mp3");
audio.play();

play audio in javascript

user3645

var audio = new Audio('audio_file.mp3');
audio.play();

play audio javascript

user9013


var bMusic = new Audio('welcome1.mp3')
	bMusic.play()

play sound in javascript

user3832

<script>
function play() {
  var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
  audio.play();
}
</script>
<button onclick-"play();">PLAY MY AUDIO</button>

how to play sound on load js

user5802

 <audio id="foobar" src="yoursample.ogg" preload="auto"> 

play sound onload react

user4431

import React, { useState, useEffect } from "react";

const useAudio = url => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

  const toggle = () => setPlaying(!playing);

  useEffect(() => {
      playing ? audio.play() : audio.pause();
    },
    [playing]
  );

  useEffect(() => {
    audio.addEventListener('ended', () => setPlaying(false));
    return () => {
      audio.removeEventListener('ended', () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = ({ url }) => {
  const [playing, toggle] = useAudio(url);

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;