<?php
/***************************************************************************

 * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
 * 
**************************************************************************/



/**
 * @file baidu_voicetrans.php 
 * @date 2022/02/28 14:32:18
 * @brief 
 **/

define("CURL_TIMEOUT",   10); 
define("URL",            "https://fanyi-api.baidu.com/api/trans/v2/voicetrans"); 
define("APP_ID",         2015063000000001);
define("SEC_KEY",        "12345678");

$voicePath = 'xxx'; //语音文件路径
$voice = base64_encode(file_get_contents($voicePath)); //base64编码
$format = 'xx'; //文件格式
$from = 'xx'; //源语种
$to = 'xx'; //目标语种
$data = translate($voice, $format, $from, $to);

/**
 * 翻译入口
 */
function translate($voice, $format, $from, $to)
{
    $args = array(
        'from' => $from,
        'to' => $to,
        'format' => $format,
        'voice' => $voice, //base64_encode
    );
    $timestamp = time();
    $sign = buildSign(APP_ID, $timestamp, $voice, SEC_KEY);
    $headers = array(
        'Content-Type: application/json',
        'X-Appid:' . APP_ID,
        'X-Sign:' . $sign,
        'X-Timestamp:'. $timestamp,
        'X-EncryptType:' . 'hmac256',
    );
    $ret = post(URL, $args, $headers);
    $ret = json_decode($ret, true);
    return $ret; 
}

/**
 * 加密
 */
function buildSign($appid, $timestamp, $voice, $secKey)
{
    $str = $appid . $timestamp . $voice;
    return base64_encode(hash_hmac('sha256', $str, $secKey, true));
}

/**
 * 发起网络请求
 */
function post($url, $args=null, $headers=array(), $timeout = CURL_TIMEOUT)
{
    $ret = false;
    $i = 0; 
    while($ret === false) 
    {
        if($i > 1)
            break;
        if($i > 0) 
        {
            sleep(1);
        }
        $ret = callOnce($url, $args, false, $timeout, $headers);
        $i++;
    }
    return $ret;
}

/**
 * curl
 */
function callOnce($url, $args=null, $withCookie = false, $timeout = CURL_TIMEOUT, $headers=array())
{
    $ch = curl_init();
    $data = json_encode($args);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    /**
     * 添加header
    */
    if(!empty($headers)) 
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    /**
     * 添加cookie
     */
    if($withCookie)
    {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
    }

    /**
     * https
     */
    if(preg_match('/^https/', $url)) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    }
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}
?>
