【问题标题】:PHP script to extract artist & title from Shoutcast/Icecast stream从 Shoutcast/Icecast 流中提取艺术家和标题的 PHP 脚本
【发布时间】:2013-03-26 01:39:17
【问题描述】:

我找到了一个脚本,它可以从 Icecast 或 Shoutcast 流中提取艺术家和标题名称。 我希望脚本在歌曲更改时自动更新,目前它只有在我执行它时才起作用。我是 PHP 新手,因此我们将不胜感激。 谢谢!

define('CRLF', "\r\n");

class streaminfo{
public $valid = false;
public $useragent = 'Winamp 2.81';

protected $headers = array();
protected $metadata = array();

public function __construct($location){
    $errno = $errstr = '';
    $t = parse_url($location);
    $sock = fsockopen($t['host'], $t['port'], $errno, $errstr, 5);
    $path = isset($t['path'])?$t['path']:'/';
    if ($sock){
        $request = 'GET '.$path.' HTTP/1.0' . CRLF . 
            'Host: ' . $t['host'] . CRLF . 
            'Connection: Close' . CRLF . 
            'User-Agent: ' . $this->useragent . CRLF . 
            'Accept: */*' . CRLF . 
            'icy-metadata: 1'.CRLF.
            'icy-prebuffer: 65536'.CRLF.
            (isset($t['user'])?'Authorization: Basic '.base64_encode($t['user'].':'.$t['pass']).CRLF:'').
            'X-TipOfTheDay: Winamp "Classic" rulez all of them.' . CRLF . CRLF;
        if (fwrite($sock, $request)){
            $theaders = $line = '';
            while (!feof($sock)){ 
                $line = fgets($sock, 4096); 
                if('' == trim($line)){
                    break;
                }
                $theaders .= $line;
            }
            $theaders = explode(CRLF, $theaders);
            foreach ($theaders as $header){
                $t = explode(':', $header); 
                if (isset($t[0]) && trim($t[0]) != ''){
                    $name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
                    array_shift($t);
                    $value = trim(implode(':', $t));
                    if ($value != ''){
                        if (is_numeric($value)){
                            $this->headers[$name] = (int)$value;
                        }else{
                            $this->headers[$name] = $value;
                        }
                    }
                }
            }
            if (!isset($this->headers['icymetaint'])){
                $data = ''; $metainterval = 512;
                while(!feof($sock)){
                    $data .= fgetc($sock);
                    if (strlen($data) >= $metainterval) break;
                }
               $this->print_data($data);
                $matches = array();
                preg_match_all('/([\x00-\xff]{2})\x0\x0([a-z]+)=/i', $data, $matches, PREG_OFFSET_CAPTURE);
               preg_match_all('/([a-z]+)=([a-z0-9\(\)\[\]., ]+)/i', $data, $matches, PREG_SPLIT_NO_EMPTY);
               echo '<pre>';var_dump($matches);echo '</pre>';
                $title = $artist = '';
                foreach ($matches[0] as $nr => $values){
                  $offset = $values[1];
                  $length = ord($values[0]{0}) + 
                            (ord($values[0]{1}) * 256)+ 
                            (ord($values[0]{2}) * 256*256)+ 
                            (ord($values[0]{3}) * 256*256*256);
                  $info = substr($data, $offset + 4, $length);
                  $seperator = strpos($info, '=');
                  $this->metadata[substr($info, 0, $seperator)] = substr($info, $seperator + 1);
                    if (substr($info, 0, $seperator) == 'title') $title = substr($info, $seperator + 1);
                    if (substr($info, 0, $seperator) == 'artist') $artist = substr($info, $seperator + 1);
                }
                $this->metadata['streamtitle'] = $artist . ' - ' . $title;
            }else{
                $metainterval = $this->headers['icymetaint'];
                $intervals = 0;
                $metadata = '';
                while(1){
                    $data = '';
                    while(!feof($sock)){
                        $data .= fgetc($sock);
                        if (strlen($data) >= $metainterval) break;
                    }
                    //$this->print_data($data);
                    $len = join(unpack('c', fgetc($sock))) * 16;
                    if ($len > 0){
                        $metadata = str_replace("\0", '', fread($sock, $len));
                        break;
                    }else{
                        $intervals++;
                        if ($intervals > 100) break;
                    }
                }
                $metarr = explode(';', $metadata);
                foreach ($metarr as $meta){
                    $t = explode('=', $meta);
                    if (isset($t[0]) && trim($t[0]) != ''){
                        $name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
                        array_shift($t);
                        $value = trim(implode('=', $t));
                        if (substr($value, 0, 1) == '"' || substr($value, 0, 1) == "'"){
                            $value = substr($value, 1);
                        }
                        if (substr($value, -1) == '"' || substr($value, -1) == "'"){
                            $value = substr($value, 0, -1);
                        }
                        if ($value != ''){
                            $this->metadata[$name] = $value;
                        }
                    }
                }
            }
            fclose($sock);
            $this->valid = true;
        }else echo 'unable to write.';
    }else echo 'no socket '.$errno.' - '.$errstr.'.';
}


public function print_data($data){
    $data = str_split($data);
    $c = 0;
    $string = '';
    echo "<pre>\n000000 ";
    foreach ($data as $char){
        $string .= addcslashes($char, "\n\r\0\t");
        $hex = dechex(join(unpack('C', $char)));
        if ($c % 4 == 0) echo ' ';
        if ($c % (4*4) == 0 && $c != 0){
          foreach (str_split($string) as $s){
            //echo " $string\n";
            if (ord($s) < 32 || ord($s) > 126){
              echo '\\'.ord($s);
            }else{
              echo $s;
            }
          }
          echo "\n";
          $string = '';
          echo str_pad($c, 6, '0', STR_PAD_LEFT).'  ';
        }
        if (strlen($hex) < 1) $hex = '00';
        if (strlen($hex) < 2) $hex = '0'.$hex;
          echo $hex.' ';
        $c++;
    }
    echo "  $string\n</pre>";
}

public function __get($name){
    if (isset($this->metadata[$name])){
        return $this->metadata[$name];
    }
    if (isset($this->headers[$name])){
        return $this->headers[$name];
    }
    return null;
 }
}

$t = new streaminfo('http://64.236.34.196:80/stream/1014'); // get metadata


echo Meta Interval: $t->icymetaint;
echo Current Track: $t->streamtitle;

【问题讨论】:

  • 感谢这个脚本。我一直在寻找那些解析流数据 HTML 页面的页面,这些页面可能会被未来版本的 Icecast/Shoutcast 破坏。 (参考:stackoverflow.com/questions/25268050/…
  • 最后两个 echo 命令抛出错误。为了纠正错误,我将它们更改为: echo "Meta Interval: ".$t->icymetaint;回声“\n”; echo '当前曲目:'.$t->streamtitle;

标签: php audio-streaming shoutcast icecast


【解决方案1】:

您将需要以设定的时间间隔不断查询流,以了解歌曲何时发生变化。

这最好通过安排cron 作业来完成。 如果在 Windows 上,您应该使用 Windows Task Scheduler

【讨论】:

【解决方案2】:

如果您想运行 PHP 脚本以使您的元数据保持最新(我假设您正在创建一个网站并在此处使用 html 音频标签),您可以使用带有 ajax 函数的 ontimeupdate 事件。如果您不是,您可能应该查看您的音频播放文档以获取类似的内容。

<audio src="http://ip:port/;" ontimeupdate="loadXMLDoc()">

你可以在这里找到一个很好的例子http://www.w3schools.com/php/php_ajax_php.asp

您想在脚本末尾使用一个 php 变量一次使用 PHP 回显函数所有相关信息。

<?php ....
$phpVar=$streamtitle;
$phpVar2=$streamsong;
$result="I want my string to look like this: <br> {$phpVar} {$phpVar2}";
echo $result;
?>

然后使用 .onreadystatechange 调用的函数,通过使用 .resonseText 修改您网站上所需的特定元素(这将包含与您的 PHP 脚本的回显相同的内容)。

【讨论】:

    【解决方案3】:

    在网上搜索了 4 小时后,这是我发现的唯一有效的 Shoutcast 元数据脚本!谢谢你。

    要持续运行,为什么不使用 setInterval 结合 jQuery 的 AJAX 调用?

    <script>
    $(function() {
        setInterval(getTrackName,16000);
    });
    
    function getTrackName() {
        $.ajax({
        url: "track_name.php"
        })
        .done(function( data ) {
        $( "#results" ).text( data );
        });
    }
    </script>
    

    您最后几句“回声”台词也为我打破了剧本。只需在元间隔等周围加上引号......

    【讨论】:

      猜你喜欢
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多