Using Zencoder with Zend Framework

Zencoder is an API-based online video and audio encoding service. Zencoder converts videos from your website, application, or video library into formats that are compatible with web playback, mobile phone, or any other device you need to support. Zencoder have friendly API and php library. We can use this library with Zend Framework after some modifications. Click here to download modified library.

First we must write js script, that will send ajax request to some Zend Framework controller and will receive response with information about created encoding job

$(document).ready(function(){
    $('#progressbar').css('width', '400px');
    $.post('/publish/zencoder', {convert: 1 }, function(data){
       if (!data) alert('Some thing wrong!');
       var html = '';
       if(data.success){
           for (i = 0; i < data.data.length; i++) {
               var  progress_bar =
                   '

<div class="progress_container">
 
<div id="progress'+data.data[i].id+'" class="progress">'+data.data[i].status.progress+'%</div>
</div>
 
 
 ';
               html = html+'
 
<div class="status'+data.data[i].id+'">'+ progress_bar+'</div>
 
 
<div id="tp2">(encoding progress)</div>
 
 
';
               $.post('/publish/zencoder', {url:  data.data[i].url},
                        function(data){ }, 'json');
               updateStatus(data.data[i].id);
            }
            $('#tp').after(html);
        }
        if(data.error){
        $('#error').text('We had a problem understanding your
                              audio file.  Please try again.');
    }
 
    }, 'json');
    return false;
})

Then write controller, that will create encoding job with some parameters, will update encoding job status or will save to session url of encoded file

public function zencoderAction()
    {
        $this-&gt;_helper-&gt;layout-&gt;disableLayout();
        $this-&gt;getHelper('viewRenderer')-&gt;setNoRender();
        $dataNamespace = new Zend_Session_Namespace('StepsNamespace');
        $convert = $this-&gt;getRequest()-&gt;getParam('convert');
        $updateStatus = $this-&gt;getRequest()-&gt;getParam('update_status');
        $url = $this-&gt;getRequest()-&gt;getParam('url');
        if(isset($convert)){
            $config = Zend_Registry::get('config');
            $inputFile = addslashes(''.$config['zencoder']['inputPath'].
                            ($dataNamespace-&gt;filename).'');
            $outputFile = addslashes(urlencode($dataNamespace-&gt;newname));
            $encoding_job = new Zencoder_ZencoderJob('
                {
                    "api_key": "'.$config['zencoder']['apiKey'].'",
                    "input": "'.$inputFile.'",
                    "outputs": [
                        {
                            "label": "Audio",
                            "url": "'.$config['zencoder']['s3Bucket'].
                            $outputFile.'.mp4",
                            "public": 1,
                            "audio_codec": "'.
                            $config['zencoder']['audioCodec'].'",
                            "audio_channels": "'.
                            $config['zencoder']['audioChannels'].'",
                            "audio_bitrate": "'.
                            $config['zencoder']['audioBitrate'].'"
 
                        }
                    ]
                }
            ');
            if ($encoding_job-&gt;created) {
            $files = array();
            $dataNamespace-&gt;id = $encoding_job-&gt;id;
            foreach ($encoding_job-&gt;outputs as $key =&gt; $value) {
                $files[]        = array('id'     =&gt; $value-&gt;id,
                                                'label' =&gt; $value-&gt;label,
                                                'url'     =&gt; $value-&gt;url,
                                                'status'=&gt;
                                                $this-&gt;checkStatus($value-&gt;id),
                                                );
            }
 
            $data = array(
                                'success' =&gt; true,
                                'job_id'    =&gt; $encoding_job-&gt;id,
                                'data'      =&gt; $files,
                                );
            } else {
                $errors = array();
                foreach($encoding_job-&gt;errors as $error) {
                    $errors[] = $error;
                }
                $data['error'] = implode(',', $errors);
            }
            $this-&gt;getResponse()-&gt;setHeader('Content-Type',
             'application/json');
            $this-&gt;_helper-&gt;json($data);
            }
        elseif(isset($updateStatus)){
            $id = $this-&gt;getRequest()-&gt;getParam('id');
            $data = $this-&gt;checkStatus($id);
            $this-&gt;getResponse()-&gt;setHeader('Content-Type',
            'application/json');
            $this-&gt;_helper-&gt;json($data);
        }
        elseif(isset($url)){
            $dataNamespace-&gt;fileext = $url;
        }
 
    }

Update encoding status script will be as follows

function updateStatus(id){
             $.post('/publish/zencoder', {update_status: 1, id: id },
                                                  function(data){
                var status = data.event;
                var status_mes = "";
                switch(status){
                    case "Downloading": status_mes = "(downloading
                                                                   progress)";
                                                         break;
                    case "Inspecting": status_mes = "(inspecting
                                                                 progress)";
                                                         break;
                    case "Transcoding": status_mes = "(transcoding
                                                                  progress)";
                                                         break;
                    case "Uploading": status_mes = "(uploading
                                                               progress)";
                                                         break;
                    case "processing": status_mes = "(processing
                                                                progress)";
                                                         break;
                }
                $('#tp2').html(status_mes);
                if(data.event != 'processing'){
                    $('#progress'+id).html(data.progress+'%');
                    $('#progress'+id).css('width', data.progress+'%');
                }
                if(!data.finished){
                    updateStatus(id);
                }else{
                     window.location.href = '/publish/audio-step2';
                }
            }, 'json');            
 
        }

And last, function that retrieves the current encoding status

  protected function checkStatus($id)
    {
        $config = Zend_Registry::get('config');
        $request = new Zencoder_ZencoderRequest(
                  'https://app.zencoder.com/api/outputs/'. $id .'/progress.xml',
                  ''.$config['zencoder']['apiKey'].''
                );
        //get progress:
        $event = '';
        $progress = '';
        preg_match_all('"]+&gt;(.*)<!--[^-->]+&gt;"',$request-&gt;raw_results, $matches);
        if(is_array($matches)){
            $event = $matches[1][0];
            @$progress = $matches[1][1];
        }
        if($progress == 'finished') $progress = 100;
        return array('successful' =&gt; $request-&gt;successful,
                            'finished'      =&gt; ($event == 'Uploading' &amp;&amp; $progress == 100) ? 1 : 0,
                            'event'          =&gt;     $event,
                            'progress'     =&gt;     $progress ? intval($progress) : 1,
                            );
    }

Official zencoder api documentation: https://app.zencoder.com/docs/api
Author: Sergey Gerashchenko

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.