Skip to content

Instantly share code, notes, and snippets.

@haykuro
Forked from fracasula/getMp3StreamTitle.php
Last active November 13, 2024 00:05
Show Gist options
  • Save haykuro/2de8d98031a3cd651754 to your computer and use it in GitHub Desktop.
Save haykuro/2de8d98031a3cd651754 to your computer and use it in GitHub Desktop.
<?php
/**
* Please be aware. This gist requires at least PHP 5.4 to run correctly.
* Otherwise consider downgrading the $opts array code to the classic "array" syntax.
*/
function getMp3StreamTitle($streamingUrl, $interval, $offset = 0, $headers = true)
{
$needle = 'StreamTitle=';
$ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
$opts = [
'http' => [
'method' => 'GET',
'header' => 'Icy-MetaData: 1',
'user_agent' => $ua
]
];
// Fetch headers to determine the metadata interval
if (($headers = get_headers($streamingUrl)))
foreach ($headers as $h)
if (strpos(strtolower($h), 'icy-metaint') !== false && ($interval = explode(':', $h)[1]))
break;
$context = stream_context_create($opts);
if ($stream = fopen($streamingUrl, 'r', false, $context))
{
while($buffer = stream_get_contents($stream, $interval, $offset)) {
if (strpos($buffer, $needle) !== false)
{
fclose($stream);
$title = explode($needle, $buffer)[1];
$title = substr($title, 1, strpos($title, ';') - 2);
// Detect the encoding of the title and convert to UTF-8
$encoding = mb_detect_encoding($title, ['UTF-8', 'ISO-8859-1', 'Windows-1252', 'ASCII'], true);
if ($encoding) {
$title = mb_convert_encoding($title, 'UTF-8', $encoding);
} else {
$title = utf8_encode($title); // Fallback in case encoding cannot be detected
}
return $title;
}
$offset += $interval;
}
}
return null; // Return null if no title is found
}
var_dump(getMp3StreamTitle('https://streamyourdream.org:8138/stream', 19200));
echo "\n\n";
?>
@haykuro
Copy link
Author

haykuro commented Nov 11, 2024

updated this gist with support for encoded character sets.

This requires the mbstring php extension to work properly.

hope that helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment