user3326523
user3326523

Reputation:

making a audio file sound in javascript/html

I am trying to play a .ogg file which i also converted into a .mp3 file

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>


<body onclick = "playSound('file:///C:/Users/Rehaan/Downloads/myfirstrecording%20(3).ogg');">

  <p id = "sound">
  </p>
  Click here to play the sound!
    </body>
</html>

This is the java script file,

function playSound( url ){   
  document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
}

Upvotes: 1

Views: 267

Answers (2)

Candost
Candost

Reputation: 1029

You can use HTML5 Tag which is <audio>. It can play .mp3, .ogg, .wav format. This is an example that I got from w3schools.

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>

Upvotes: 1

416E64726577
416E64726577

Reputation: 2214

I would recommend using the HTML5 audio tag.

      <audio id="audio_samples" src="mymp3audiofile.mp3" controls></audio> 

The audio tag supports mp3, ogg, and wav audio files.



Also, here are Javascript audio control functions that you may find useful:

      <script type="text/javascript">
        var audio = document.getElementById("audio_samples");
                  
                  
        function playAudio() {
            audio.play();    
        }

        function pauseAudio() {
            audio.pause();    
        }
        
        function restartAudio() {
            audio.load(); 
            audio.play();
        }
        
        function louder() {
            audio.volume += 0.1;
        }
        
        function softer() {
            audio.volume -= 0.1;
        }
      </script>
      
      <button onclick="playAudio()">Play</button>
      <button onclick="pauseAudio()">Pause</button>
      <button onclick="restartAudio()">Restart</button>
      <button onclick="louder()">Louder</button>
      <button onclick="softer()">Softer</button>

I hope this helps!

Upvotes: 2

Related Questions