<?php
// Set headers for continuous MP3 stream
header('Content-Type: audio/mpeg');
header('Cache-Control: no-cache');
header('Pragma: no-cache');

// Function to get file size
function getFileSize($filename) {
    return filesize($filename);
}

// Get all MP3 files
$mp3Files = glob('*.mp3');
if (empty($mp3Files)) {
    die('No MP3 files found');
}

// Shuffle the playlist once
shuffle($mp3Files);

// Calculate total size for Content-Length header
$totalSize = 0;
foreach ($mp3Files as $file) {
    $totalSize += getFileSize($file);
}
header('Content-Length: ' . $totalSize);

// Stream each file once
foreach ($mp3Files as $file) {
    $handle = fopen($file, 'rb');
    if ($handle === false) {
        continue; // Skip if file can't be opened
    }
    
    // Stream the file in chunks
    while (!feof($handle)) {
        $data = fread($handle, 8192);
        if ($data === false) {
            break; // Break if read fails
        }
        echo $data;
        flush();
        
        // Check connection status
        if (connection_status() != CONNECTION_NORMAL) {
            fclose($handle);
            exit;
        }
    }
    fclose($handle);
}

// End the script after all files have been played
exit;
?>
