/** * 生成语音文件 * @param string $name * @return string 语音数据 */ public function buildAudio($name = null) { $text_length = mb_strlen($this->tex, 'utf-8'); $texParts = []; $index = 0; $max_index = ceil($text_length / self::TEXT_LIMIT) - 1; while ($index <= $max_index) { $texParts[] = mb_substr($this->tex, $index * self::TEXT_LIMIT, self::TEXT_LIMIT, 'utf-8'); $text_length -= self::TEXT_LIMIT; $index++; } $requests = array(); $counter = 1; foreach ($texParts as $tex) { $post_data = array('tex' => $this->doubleUrlencode($tex), 'lan' => $this->lan, 'tok' => $this->doubleUrlencode($this->tok), 'ctp' => $this->ctp, 'cuid' => $this->doubleUrlencode($this->cuid), 'spd' => $this->spd, 'pit' => $this->pit, 'vol' => $this->vol, 'per' => $this->per); $requests[] = array('url' => self::API_URL, 'options' => array(CURLOPT_HEADER => true, CURLOPT_POSTFIELDS => $this->buildPostBody($post_data))); $counter++; } // var_dump($requests); $Request = new Request(); $Request->setMethod('post'); $Request->setAsynRequests($requests); try { $Request->sendRequestAsyn(); $responses = $Request->getAsynResponses(); // var_dump($responses); // var_dump($post_data); // var_dump($Request->responseBody()); if ($this->enableCache) { if ($this->mergeAudio === true) { $audio_cache_name = $this->pathJoin($this->cacheRoot, $name . '.mp3'); } else { $audio_cache_dir = $this->pathJoin($this->cacheRoot, $name); } self::clearAudio($this->cacheRoot, $name, false); } $audio = ''; $counter = 1; foreach ($responses as $response) { if ($response->responseHeaders['content-type'] == 'audio/mp3') { $audio .= $response->responseBody; if ($this->enableCache) { if ($this->mergeAudio === true) { try { $this->cacheMergeAudio($response->responseBody, $audio_cache_name); } catch (Exception $e) { $this->error = $e->getMessage(); return false; } } else { try { $this->cacheAudio($response->responseBody, $audio_cache_dir, $counter . '.mp3'); } catch (Exception $e) { $this->error = $e->getMessage(); return false; } } } } elseif (strpos($response->responseHeaders['content-type'], 'json')) { $error = json_decode($response->responseBody, true); $this->error = $error['err_msg']; return false; } else { $this->error = 'Unkown error'; return false; } $counter++; } return $audio; } catch (Exception $e) { $this->error = $e->getMessage(); return false; } }