Enable audio seeking HTML5 audio and MediaElement.js players with PHP served source

StackOverflow https://stackoverflow.com/questions/18369735

  •  26-06-2022
  •  | 
  •  

Pergunta

I set up an MP3 audio player with MediaElement.js and it will not allow me to seek whereas the demo at mediaelementjs.com does allow seeking. I don't see any options or instruction about enabling seeking on the website. Why won't it seek?

I'm using version 2.13.1. Here is the code (except for the included js and css files):

<audio controls="control" preload="auto" src="sound.mp3" type="audio/mp3"></audio>
<script>
$('audio').mediaelementplayer();
</script>

Edit: I found the problem to be how I served the audio file via PHP. I didn't mention this before, but I've changed the question title to include this. The MP3 file is being served via PHP readfile() in order to protect it from download by non-members.

Foi útil?

Solução

If you are serving your audio files via PHP for the HTML5 audio element and other players such as MediaElement.js, you need to include the following header for seeking to work:

<?php header('Accept-Ranges: bytes'); ?>

Here's my php to serve the file:

if(file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$filename);
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    header('Accept-Ranges: bytes');
    flush();
    readfile($file);
    exit();
}

Of course, you need to set $file (file path) and $filename (just the file name).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top