본문 바로가기

개나소나 프로그램 개발/PHP 개발

네이버 오픈API 음성합성 API 사용하는 PHP 샘플코드를 만들어봄..

* 네이버 오픈API를 사용하려면 먼저 API 사용신청을 해야 합니다.



네이버 음성합성 API  PHP 샘플


 

<?

//<-- 네이버 오픈API 음성합성 API  사용

header("Content-Type:text/html; charset=utf-8");

header("Content-Encoding:utf-8");

//ini_set('memory_limit', '256M');

//<-- 음성합성API를 사용하는 어플리케이션 등록후 발급받은 ID와 KEY 값을 입력

$clientID  = "클라이언트ID";

$secretKey = "시크릿키";

$ttsURL  = "https://openapi.naver.com/v1/voice/tts.bin";



 $ch = curl_init();

 

 $text = "안녕하세요. 네이버 TTS 샘플 입니다.";


  //<-- 음성합성 파라미터 설정 (남성,여성 보이스 선택,  말하기 속도 설정)

  $fields = array('speaker'=>'mijin','speed'=>'0', 'text'=>$text);

  $postvars = '';

  foreach($fields as $key=>$value) {

        $postvars .= $key . "=" . $value . "&";

  }

  

$headers = array();

$headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';

$headers[] = 'X-Naver-Client-Id: '.$clientID.'';

$headers[] = 'X-Naver-Client-Secret: '.$secretKey.'';

$headers[] = 'Cache-Control: no-cache';

$headers[] = 'User-Agent: curl/7.43.0';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

 


curl_setopt($ch,CURLOPT_URL,$ttsURL);

curl_setopt($ch,CURLOPT_POST, 1);                

curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);

curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,10);

curl_setopt($ch,CURLOPT_TIMEOUT, 20);

  

$response = curl_exec($ch);  //<-- 네이버 음성합성 API 요청하여 결과데이타를 mp3로 받는다.

curl_close ($ch);

  

//<--받은 파일을 쓰기 가능한 경로의 파일명으로 저장한다..  

$destination = "../upload/sample1.mp3";

$file = fopen($destination, "w+");

fputs($file, $response);

fclose($file);  



?>


* curl 실행시 HTTP HEADER 에 API ID,KEY 값 넣는것 때문에 잠깐 헤맸는데  비교적 쉽게 구현..

* 음성합성된 결과 MP3의  음질도 괜찮은 편임..

* 네이버 API 설명 페이지에는 샘플이 없어서 간단하게 만들었음..


2016/3/12   개나소나 개발자..