user9348468
user9348468

Reputation:

AMR audio not playing in browser, html generated via javascript

Via javascript, I am trying to create the HTML and play an audio file but it's not playing.

If I download that same file and play it via a media player, it plays. My attempt is as below.

var audio = document.createElement("audio");
audio.src = "/files/chat-space/4928f76ff3258fcca32bb75d5d043237";
audio.play();

Is there any way to play this audio inside the browser, even using some other js-supported media player?

Upvotes: 1

Views: 1042

Answers (3)

cssyphus
cssyphus

Reputation: 40028

Try:

<script type="text/javascript">
    window.addEventListener('load', () => {
        var audio = document.createElement("audio");
        var asrc = document.createElement("source");
        asrc.setAttribute('src', "/files/chat-space/4928f76ff3258fcca32bb75d5d043237");
        audio.appendChild(asrc);
        audio.play();
    });
</script>

Notes:

The window.addEventListener('load') tells the page not to try playing the audio until all HTML and resources are loaded/available.

The audio tag does not have a src= attribute — it has a child element, <source>, and that element has the src= attribute.

FWIW, I just tested the above code on a live server, using a standard mp3 audio file. If this code does not work for you, first try it with a standard .mp3 file (to ensure the problem is not with specifying the audio file).

If it still doesn't work, please tell us more about your environment.

See:

https://www.w3schools.com/TAGS/tag_audio.asp

Upvotes: 0

Azeroth
Azeroth

Reputation: 11

You can use Audio class in JS

var audio = new Audio('audio_file.mp3'); // file must be having mp3 format
audio.play();

Upvotes: 0

Sai
Sai

Reputation: 76

Writing the error you're receiving by @ZeroWorks comment would make it much easier, and without an actual example I can only answer it as a guess.

I assume the error you're getting is "play() failed because the user didn't interact with the document first."

I don't know what you're trying to do, but one solution for that could be 'forcing' the client to interact with the document using a button element.

For example:

<script>
    function onClick() {
        var audio = document.createElement("audio");
        audio.src = "./mediaFile.mp3";
        audio.play();
    }
</script>

Then have the following button element:

<button onclick="onClick()"> Click me </button>

If this is not your issue please try to explain it more precisely.

Upvotes: 2

Related Questions