Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - AngularJS stream audio from PHP server 2

I have the following PHP code which authenticate to a third-party server using JWT and download the recorded audio from the server and then it serves the .mp3 to javascript which constructs an Audio object to playback the audio. How to do this more efficiently?

use LcobucciJWTBuilder;
use LcobucciJWTSignerKey;
use LcobucciJWTSignerRsaSha256;
private function generate_jwt() {
    $dev = preg_match("/blah.blah.com/", $_SERVER["HTTP_HOST"]);
    $jwt = false;
    date_default_timezone_set('UTC');    //Set the time for UTC + 0
    //$key = file_get_contents($keyfile);  //Retrieve your private key
    $key = $dev ? self::DEV_KEY : self::PRODUCTION_KEY;
    $id = $dev ? self::DEV_ID : self::PRODUCTION_ID;
    $signer = new Sha256();
    $privateKey = new Key($key);
    $jwt = (new Builder())->setIssuedAt(time() - date('Z')) // Time token was generated in UTC+0
        ->set('application_id', $id) // ID for the application you are working with
        ->setId( base64_encode( mt_rand (  )), true)
        ->sign($signer,  $privateKey) // Create a signature using your private key
        ->getToken(); // Retrieves the JWT
    return $jwt;
}
public function playback($url) {
    $response = "";
    if (!empty($url)) {
        //Create your JWT
        $jwt = $this->generate_jwt();
        //Add the JWT to your headers
        $headers =  array('Content-Type: application/json', "Authorization: Bearer " . $jwt);
        $ch = curl_init();
        //Make a request to $recording_url
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        $file = __TMPDIR__ . basename($url).".mp3";
        file_put_contents($file, $response);
        header('Pragma: public');   // required
        header('Content-Type: audio/mpeg');
        header('Content-length: ' . filesize($file));
        header("Content-Transfer-Encoding: binary");
        header('Content-Disposition: filename="' . basename($file));
        header('X-Pad: avoid browser bug');
        header('Cache-Control: no-cache');
        $len = readfile($file);
    } else
        error_log(__FILE__." ".__FUNCTION__." ".__LINE__.": Invalid url! ".$url);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...