Mohammad
Mohammad

Reputation: 159

set the currentTime in HTML5 audio not working properly

I built a Music Player in my project and everything works fine.
but in some mp3 files I can't set currentTime of Audio element.
for exmaple in this code:

src = "music path";
const audioElement = new Audio(src);
let playPromise = audioElement.play();
if (playPromise!==undefined){
    playPromise.then(function() {
        // promised audio started
        audioElement.currentTime = 20;
        console.log(audioElement.currentTime);

        }).catch(function(error) {
        // promised audio failed
    });
}

Program Result => 0
when I'm setting the new currentTime, The audio starts from the beginning and time goes to zero.
Audio file is safe and its duration is 120 seconds, so this issue is not for lack of audio duration.
I googled a bit about this problem and realized that some settings should be made in the Http Headers. Actually I don't know what is this at all! but I figured that I need to set this settings properly:

accept-ranges: bytes

Content-Length: BYTE_LENGTH_OF_YOUR_FILE

Content-Range: bytes 0-BYTE_LENGTH_OF_YOUR_FILE/BYTE_LENGTH_OF_YOUR_FILE

content-type: audio/mp3

UPDATE > SOLUTION
Finally, after days, I solved this problem and I also realized that it is a very common problem among Django framework users.
All we need is to first send our music file to the client via FileResponse and also make some settings in the HTTP headers section.

from django.http import FileResponse

response = FileResponse(Object.mp3)
response["Content-Disposition"] = f"filename={Object.name}.mp3"
response["Content-Type"] = "audio/mp3"
response["Content-Length"] = os.path.getsize(Object.mp3.path)
response["Accept-Ranges"] = "bytes"
return response

Don't forget Accept-Ranges and Content-Length Setting. They are very Important!

Upvotes: 1

Views: 315

Answers (1)

hub246
hub246

Reputation: 36

The header of an audio file is like a preface or introduction to it, it lists informations such as the length of the audio file, it's format, encoding method (used to reduce file size) and other data that is needed to play it.

You can modify pretty easily audio files and their associated header with an audio editing software (Audacity for example).

As for your code, you could maybe use .addEventListener to add an event to your audioElement const with the 'canplay' event, which is triggered if and when an audio file can be played on the browser.

For example: audioElement.addEventListener('canplay', function() {[your code here]}

Upvotes: 1

Related Questions