Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RadioWave - Live song name from streaming server
<div>Now playing: <span id="currentlyPlaying">[song info loading...]</span></div>
<script>
var url = '/path/to/get_songs.php';
function updateTitle() {
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
if (data.length) {
var name = data[0].name;
document.getElementById('currentlyPlaying').innerHTML = name;
}
})
.catch(function(e) {
console.log(e);
});
}
updateTitle();
var repeat = setInterval(function(){updateTitle();}, 10*1000);
</script>
<?php
// get_songs.php
// Convert raw/html song listing to a JSON object
$dataURL = '/path/to/songs/list.php';
$getData = file_get_contents($dataURL);
preg_match("#<div id=\"main\">(.*?)</div>#s", $getData, $matches);
$songs = preg_replace("#(\r|\n|\t)#s", "", trim($matches[1]));
$songs = explode('<br />', $songs);
$json = array();
foreach ($songs as $key => $song) {
$songParts = explode(" ", $song);
$time = $songParts[0];
$name = implode(" ", array_slice($songParts, 1));
$json[] = array('time' => $time, 'name' => $name);
}
//$data = 'radiowave_playing('.json_encode($json).');'; // Uncomment if you wish to output JSONP
$data = json_encode($json);
$expires = 0;
ob_start("ob_gzhandler");
echo $data;
$bufferSize = ob_get_length(); // Required to close the connection
header("Content-Type: application/javascript; charset=UTF-8");
header("Cache-Control: public, max-age=".($expires*60).", stale-while-revalidate=".($expires*60*2).", stale-if-error=".($expires*60*3));
header("Expires: ".gmdate("D, d M Y H:i:s", time() + ($expires*60))." GMT");
header("Access-Control-Allow-Origin: *");
header("Content-Length: $bufferSize");
header("Connection: close");
ob_end_flush();
ob_flush();
flush();
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.