<?php
    date_default_timezone_set
("Pacific/Auckland");
    
header('Content-Type: application/json');

    
$data = array();
        
$local_cache "/your/local/folder/";
        
$cache_url "http://the.server.address/folder/";

    
//what's the current time?
    
$current_time date("U");

    
//format the date / time to how Radio NZ names their file
    
$time_string date("Ymd-H00"$current_time);
    
$filename $time_string "-048.mp3";

    
//do we already have this script processed? If so, don't do anything else
    
if(!file_exists($local_cache $filename))
    {
        
//does the file exist at RNZ? If so, we'll process it now
        
$file_url "http://on-demand.radionz.co.nz/news/" $filename;
        if(
UR_exists($file_url))
        {
            
//get the stream
            
$filedata file_get_contents($file_url);
            
$result file_put_contents('/tmp/'.$filename$filedata);

            
//convert the loudness
            
$command "/usr/local/bin/sox /tmp/" $filename " -C 64 " $local_cache$filename " gain -b -n -1 silence 1 0.1 1% reverse silence 1 0.1 1% reverse";
            
$result exec($command);
            
//remove the temp file
            
unlink('/tmp/' $filename);
        }
    }

function 
UR_exists($url){
    
//function copied from Patrick at StackOverflow
    //http://stackoverflow.com/questions/7684771/how-check-if-file-exists-from-the-url
   
$headers=get_headers($url);
   return 
stripos($headers[0],"200 OK")? true:false;
}
?>