Progress bar resets when clicked, file stream through PHP
Answers
-
The issue where clicking on the progress bar resets the audio playback to the beginning could be caused by how the audio file is being streamed. Browsers typically use HTTP range requests to allow seeking within a file (like when a user clicks on the progress bar of an audio player). If the server does not support range requests, the browser may only be able to start the audio from the beginning.
To fix this, you need to implement support for range requests in your PHP script. Here's an updated version of the code to handle HTTP range requests, allowing for seeking within the audio file:
<?php // Path to your audio file $audioFile = 'path/to/your-audio-file.mp3'; // Check if the file exists if (!file_exists($audioFile)) { // If the file doesn't exist, return a 404 response http_response_code(404); echo "File not found."; exit; } // Get the file size $filesize = filesize($audioFile); $length = $filesize; // Content length to be sent $start = 0; // Start byte $end = $filesize - 1; // End byte // Check if the client sent the Range header (for seeking) if (isset($_SERVER['HTTP_RANGE'])) { // Parse the Range header $range = $_SERVER['HTTP_RANGE']; $range = str_replace('bytes=', '', $range); $range = explode('-', $range); // Calculate the start and end positions $start = (int)$range[0]; $end = ($range[1] != '') ? (int)$range[1] : $end; // Adjust content length for the range requested $length = $end - $start + 1; // Send 206 Partial Content header header('HTTP/1.1 206 Partial Content'); } else { // Send 200 OK header if no Range was requested header('HTTP/1.1 200 OK'); } // Set the headers for file streaming header('Content-Type: audio/mpeg'); // Adjust MIME type if needed header('Content-Length: ' . $length); header('Content-Range: bytes ' . $start . '-' . $end . '/' . $filesize); header('Accept-Ranges: bytes'); header('Content-Disposition: inline; filename="' . basename($audioFile) . '"'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Expires: 0'); // Open the file $fp = fopen($audioFile, 'rb'); // Move the pointer to the start of the requested range fseek($fp, $start); // Stream the file content in chunks $bufferSize = 1024 * 8; // 8KB buffer while (!feof($fp) && ($pos = ftell($fp)) <= $end) { if ($pos + $bufferSize > $end) { $bufferSize = $end - $pos + 1; } // Output the current buffer echo fread($fp, $bufferSize); flush(); // Ensure the buffer is sent to the client } // Close the file fclose($fp); exit; ?>
0
Howdy, Stranger!
Categories
- 94 All Categories
- 20 VoIP
- 7 SIP
- 16 asterisk
- 44 Programming
- 1 Nodejs
- 4 javascript
- 19 PHP
- 8 Codeigniter
- 14 database
- 1 UI/UX
- 2 Flutter
- 28 OS
- 26 Linux
- 1 Virtualization
- 1 Android
- 1 Windows
- 2 legal