Тест SpeechKit Cloud API от компании Yandex.

YANDEX SPEECHKIT PHP ПРИМЕР

Yandex SpeechKit — это набор функций, который позволяет производить синтез и распознавание текста на русском языке. С помощью этого инструмента можно создавать голосовые модули, chat-ботов и другие проекты на PHP.

Для работы с Yandex SpeechKit на PHP необходимо выполнить следующие шаги:

  1. Зарегистрироваться на сайте Яндекс.Облако и создать SpeechKit API-клиент
  2. Установить библиотеку Guzzle (которая используется для HTTP-запросов)
  3. Написать код для HTTP-запроса к API SpeechKit

Приведем пример кода на PHP для преобразования текста в речь:

$httpClient = new \GuzzleHttp\Client();
$response = $httpClient->request(‘POST’, ‘https://tts.api.cloud.yandex.net/speech/v1/tts:synthesize’, [
‘headers’ => [
‘Authorization’ => ‘Bearer YOUR_IAM_TOKEN’,
‘Content-Type’ => ‘application/x-www-form-urlencoded’
],
‘body’ => ‘text=Привет, мир!&lang=ru-RU&folderId=b1gjevk697q4klstbpt9’
]);

Диктор бесплатно нужен? Заказать можно онлайн на яндекс speechkit

Пишем скрипт переводчик пользующийся yandex translate без api. PHP curl регулярки в прямом эфире.

Yandex Speechkit + Python = Синтез озвучки из текста, API

Подключение к сервису Yandex SpeechKit

Как две Алисы поругались между собой )

Инструкция по настройке проекта с сервисом Yandex SpeechKit

Yandex SpeechKit Brand Voice: технология, с которой компании обретают голос

Источник

Применение SpeechKit Cloud API для озвучивания погоды и новостей от Yandex

Добрый день! В данной статье хотелось бы рассказать о том, как можно сделать на сайте «Голосовой погодный и новостной информер», который бы, например при выборе города не только показывал, но и рассказывал фактический прогноз погоды, а так же произвольную новость. На самом деле этот скрипт разрабатывался для информирования в системе «Умный Дом», но может быть с легкостью переделан под любой сайт, имеющий на хостинге поддержку PHP, что и было сделано для этой статьи. В примере для синтеза речи, будет использоваться технология SpeechKit Cloud API от компании Yandex и XML парсер Yandex погоды и новостей, написанные на PHP.

  • Web сервер с поддержкой PHP (можно локальный типа Денвера).
  • Ключ Yandex SpeechKit (для некоммерческих проектов можно получить бесплатно).
  • Если ключ не дают без наличия у Вас сайта, то создать сайт можно на Hostinger.ru.
  • Список ID городов.
  • Отправляем запрос на получение mp3 файла, для выбранного города.
  • Парсим XML файл, получая необходимые параметры.
  • Корректируем окончания слов, для постановки правильного произношения.
  • Устанавливаем параметры генерации mp3 файла (голос, тембр, формат файла, язык, текст).
  • Генерируем mp3 файл.
  • Создаем объект Audio HTML 5 и воспроизводим файл.
      

Тест SpeechKit Cloud API от компании Yandex.

Погода

Новости

Горда можно добавлять путём установки новых параметров option в элементе select.

fact->temperature; // температура $weather_type=$xml->fact->weather_type; // тип погоды $humidity=$xml->fact->humidity; // влажность $wind_direction=$xml->fact->wind_direction; // направление ветра $wind_speed=$xml->fact->wind_speed; // скорость ветра $pressure=$xml->fact->pressure; // давление $znak="плюс"; if($wind_direction=="e") < $wind_direction_text="восточный";>if($wind_direction=="w") < $wind_direction_text="западный";>if($wind_direction=="s") < $wind_direction_text="южный";>if($wind_direction=="n") < $wind_direction_text="северный";>if($wind_direction=="se") < $wind_direction_text="юго-восточный";>if($wind_direction=="ne") < $wind_direction_text="северо-восточный";>if($wind_direction=="sw") < $wind_direction_text="юго-западный";>if($wind_direction=="nw") < $wind_direction_text="северо-западный";>$minus_arry=preg_match("/(-)/", $temp, $minus_out); if (!empty($minus_out[1])) < $znak="минус"; $temp=str_replace("-","",$temp); >//градус if( $temp=="1" or $temp=="21" or $temp=="31" or $temp=="41" or $temp=="51" or $temp=="61" or $temp=="71" or $temp=="81" or $temp=="91" or $temp=="101") < $text="градус"; >else < //градуса if( $temp=="2" or $temp=="3" or $temp=="4" or $temp=="22" or $temp=="23" or $temp=="24" or $temp=="32" or $temp=="33" or $temp=="34" or $temp=="42" or $temp=="43" or $temp=="44" or $temp=="52" or $temp=="53" or $temp=="54" or $temp=="62" or $temp=="63" or $temp=="64" or $temp=="72" or $temp=="73" or $temp=="74" or $temp=="82" or $temp=="83" or $temp=="84" or $temp=="92" or $temp=="93" or $temp=="94" or $temp=="102" or $temp=="103" ) else > //процент if( $humidity=="1" or $humidity=="21" or $humidity=="31" or $humidity=="41" or $humidity=="51" or $humidity=="61" or $humidity=="71" or $humidity=="81" or $humidity=="91" or $humidity=="101") < $humidity_text="процент"; >else < //процента if( $humidity=="2" or $humidity=="3" or $humidity=="4" or $humidity=="22" or $humidity=="23" or $humidity=="24" or $humidity=="32" or $humidity=="33" or $humidity=="34" or $humidity=="42" or $humidity=="43" or $humidity=="44" or $humidity=="52" or $humidity=="53" or $humidity=="54" or $humidity=="62" or $humidity=="63" or $humidity=="64" or $humidity=="72" or $humidity=="73" or $humidity=="74" or $humidity=="82" or $humidity=="83" or $humidity=="84" or $humidity=="92" or $humidity=="93" or $humidity=="94" or $humidity=="102" or $humidity=="103" ) else > //миллиметр if( $pressure=="701" or $pressure=="721" or $pressure=="731" or $pressure=="741" or $pressure=="751" or $pressure=="761" or $pressure=="771" or $pressure=="781" or $pressure=="791" or $pressure=="801") < $pressure_text="милиметр ртутного столба"; >else < //миллиметра if( $pressure=="702" or $pressure=="703" or $pressure=="704" or $pressure=="722" or $pressure=="723" or $pressure=="724" or $pressure=="732" or $pressure=="733" or $pressure=="734" or $pressure=="742" or $pressure=="743" or $pressure=="744" or $pressure=="752" or $pressure=="753" or $pressure=="754" or $pressure=="762" or $pressure=="763" or $pressure=="764" or $pressure=="772" or $pressure=="773" or $pressure=="774" or $pressure=="782" or $pressure=="783" or $pressure=="784" or $pressure=="792" or $pressure=="793" or $pressure=="794" or $pressure=="802" or $pressure=="803" ) else > $say_text="Сейчас в городе ".$city." ".$weather_type.". Tемпература воздуха ".$znak." ".$temp." ".$text.". Влажность ".$humidity." ".$humidity_text.". Ветер ".$wind_direction_text." ".$wind_speed." метров в секунду. Атмосферное давление ".$pressure." ".$pressure_text." !"; $qs = http_build_query(array("format" => "mp3","lang" => "ru-RU","speaker" => "jane","key" => "SpeechKit_Cloud_API_Key","emotion" => "good", "text" => $say_text)); // параметры запроса $ctx = stream_context_create(array("http"=>array("method"=>"GET","header"=>"Referer: \r\n"))); $soundfile = file_get_contents("https://tts.voicetech.yandex.net/generate?".$qs, false, $ctx); // запрос на генерацию mp3 файла echo($soundfile); ?> 
channel->item[$number]->description; //новость $title=$xml->channel->item[$number]->title; //заголовок $content_news = trim(preg_replace('/\s/', ' ', $news));//удаляем весь хлам $content_title = trim(preg_replace('/\s/', ' ', $title));//удаляем весь хлам $text=$content_title." - ".$content_news; $search = array('"','"',' ',')','('); $replace = array(''); $text = str_replace($search, $replace, $text); $qs = http_build_query(array("format" => "mp3","lang" => "ru-RU","speaker" => "jane","key" => "SpeechKit_Cloud_API_Key","emotion" => "good", "text" => $text)); // параметры запроса $ctx = stream_context_create(array("http"=>array("method"=>"GET","header"=>"Referer: \r\n"))); $soundfile = file_get_contents("https://tts.voicetech.yandex.net/generate?".$qs, false, $ctx); // запрос на генерацию mp3 файла echo($soundfile); ?> 

В скрипте нужно изменить SpeechKit_Cloud_API_Key на полученный Вами ключ. Данную технологию можно также использовать и для озвучивания даты и времени. Есть возможность изменять язык, тембр, голоса (мужские и женские), описание всех параметров синтеза речи можно посмотреть по ссылке на SpeechKit Cloud API которая находится ниже.
Приведенные выше скрипты, тестировались в браузерах Google Chrome и Iceweasel, но должны корректно работать и в других браузерах с поддержкой HTML 5 Web Audio.

Читайте также:  Sign Up

P.S. Используемая литература

Публикация Яндекс.ТвояПогода
Погода от Yandex
Новости от Yandex
SpeechKit Cloud API
Проверить работу SpeechKit Cloud API можно тут. Посмотреть на Youtube, что получилось (пример в начале 7-ой минуты — синтез речи с помощью RHVoice ).

Написанный код не претендует на идеальность и его всегда можно доработать.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

ZloeSabo/speechkit-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Scrutinizer Code Quality Code Coverage

SpeechKit uses Composer, please checkout the composer website for more information.

Add SpeechKit in your composer.json and you can go ahead:

composer require zloesabo/speechkit-php

SpeechKit follows the PSR-4 convention names for its classes, which means you can easily integrate SpeechKit classes loading in your own autoloader.

Usage of previous version is strongly discouraged as it lacked concept and testing. However, if you sure you want to use previous version of library, require it with composer require zloesabo/speechkit-php:~1.0

// Include dependencies installed with composer require 'vendor/autoload.php'; use SpeechKit\Response\HypothesesList; use SpeechKit\Response\Hypothesis; use SpeechKit\Speech\SpeechContent; use SpeechKit\SpeechKit; $key = 'your-key-here'; $speechKit = new SpeechKit($key); //It can be any type of stream. File, string, instance of StreamInterface, etc. $source = fopen(__DIR__.'/some/path/to/file.mp3', 'r'); $speech = new SpeechContent($source); //Defaults will be used: mp3, general topic, russian language /** @var HypothesesList $result */ $result = $speechKit->recognize($speech); /** @var Hypothesis $hyphotesis */ foreach ($result as $hyphotesis) < echo sprintf( 'Confidence: %.2f Content: %s', $hyphotesis->getConfidence(), $hyphotesis->getContent() ), PHP_EOL; >
require 'vendor/autoload.php'; use SpeechKit\Client\Curl; use SpeechKit\Response\HypothesesList; use SpeechKit\Response\Hypothesis; use SpeechKit\ResponseParser\SimpleXML; use SpeechKit\Speech\SpeechContent; use SpeechKit\Speech\SpeechContentInterface; use SpeechKit\SpeechKit; use SpeechKit\Uploader\Uploader; use SpeechKit\Uploader\UrlGenerator; $key = 'your-key-here'; $urlGenerator = new UrlGenerator($key); //You could use any type of client which implements ClientInterface $client = new Curl(); $uploader = new Uploader($urlGenerator, $client); //You could use any type of parser which implements ResponseParserInterface $responseParser = new SimpleXML(); $speechKit = new SpeechKit($key, $uploader, $responseParser); $source = fopen(__DIR__.'/some/path/to/file.mp3', 'r'); $speech = new SpeechContent($source); //These settings are default, so you can skip setting them $speech->setContentType(SpeechContentInterface::CONTENT_MP3); $speech->setTopic(SpeechContentInterface::TOPIC_GENERAL); $speech->setLang(SpeechContentInterface::LANG_RU); $speech->setUuid(bin2hex(openssl_random_pseudo_bytes(16))); /** @var HypothesesList $result */ $result = $speechKit->recognize($speech); /** @var Hypothesis $hyphotesis */ foreach ($result as $hyphotesis) < echo sprintf( 'Confidence: %.2f Content: %s', $hyphotesis->getConfidence(), $hyphotesis->getContent() ), PHP_EOL; >

About

Источник

Оцените статью