CLOVA Voice 예제
- 인쇄
- PDF
CLOVA Voice 예제
- 인쇄
- PDF
기사 요약
이 요약이 도움이 되었나요?
의견을 보내 주셔서 감사합니다.
Classic/VPC 환경에서 이용 가능합니다.
CLOVA Voice TTS (Premium) API를 사용하는 예제를 소개합니다.
CLOVA Voice TTS (Premium)
변환할 텍스트와 음색, 속도, 감정 등을 파라미터로 입력받아 음성을 합성하는 CLOVA Voice API 예제를 설명합니다.
Java
Java 기반의 CLOVA Voice API 예제 코드는 다음과 같습니다.
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
public class APIExamTTS {
public static void main(String[] args) {
String clientId = "YOUR_CLIENT_ID";//애플리케이션 클라이언트 아이디값";
String clientSecret = "YOUR_CLIENT_SECRET";//애플리케이션 클라이언트 시크릿값";
try {
String text = URLEncoder.encode("만나서 반갑습니다.", "UTF-8"); // 13자
String apiURL = "https://naveropenapi.apigw.ntruss.com/tts-premium/v1/tts";
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
// post request
String postParams = "speaker=nara&volume=0&speed=0&pitch=0&format=mp3&text=" + text;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode==200) { // 정상 호출
InputStream is = con.getInputStream();
int read = 0;
byte[] bytes = new byte[1024];
// 랜덤한 이름으로 mp3 파일 생성
String tempname = Long.valueOf(new Date().getTime()).toString();
File f = new File(tempname + ".mp3");
f.createNewFile();
OutputStream outputStream = new FileOutputStream(f);
while ((read =is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
is.close();
} else { // 오류 발생
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Python
Python 기반의 CLOVA Voice API 예제 코드는 다음과 같습니다.
import os
import sys
import urllib.request
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
encText = urllib.parse.quote("반갑습니다 네이버")
data = "speaker=nara&volume=0&speed=0&pitch=0&format=mp3&text=" + encText;
url = "https://naveropenapi.apigw.ntruss.com/tts-premium/v1/tts"
request = urllib.request.Request(url)
request.add_header("X-NCP-APIGW-API-KEY-ID",client_id)
request.add_header("X-NCP-APIGW-API-KEY",client_secret)
response = urllib.request.urlopen(request, data=data.encode('utf-8'))
rescode = response.getcode()
if(rescode==200):
print("TTS mp3 저장")
response_body = response.read()
with open('1111.mp3', 'wb') as f:
f.write(response_body)
else:
print("Error Code:" + rescode)
import os
import sys
import urllib
import urllib2
reload(sys)
sys.setdefaultencoding('utf-8')
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
text = unicode("반갑습니다 네이버")
speaker = "nara"
speed = "0"
volume = "0"
pitch = "0"
fmt = "mp3"
val = {
"speaker": speaker,
"volume": volume,
"speed":speed,
"pitch": pitch,
"text":text,
"format": fmt
}
data = urllib.urlencode(val)
url = "https://naveropenapi.apigw.ntruss.com/tts-premium/v1/tts"
headers = {
"X-NCP-APIGW-API-KEY-ID" : client_id,
"X-NCP-APIGW-API-KEY" : client_secret
}
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
rescode = response.getcode()
if(rescode==200):
print("TTS mp3 save")
response_body = response.read()
with open('1111.mp3', 'wb') as f:
f.write(response_body)
else:
print("Error Code:" + rescode)
PHP
PHP 기반의 CLOVA Voice API 예제 코드는 다음과 같습니다.
<?php
$client_id = "YOUR_CLIENT_ID";
$client_secret = "YOUR_CLIENT_SECRET";
$encText = urlencode("반갑습니다.");
$postvars = "speaker=nara&volume=0&speed=0&pitch=0&format=mp3&text=".$encText;
$url = "https://naveropenapi.apigw.ntruss.com/tts-premium/v1/tts";
$is_post = true;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, $is_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $postvars);
$headers = array();
$headers[] = "X-NCP-APIGW-API-KEY-ID: ".$client_id;
$headers[] = "X-NCP-APIGW-API-KEY: ".$client_secret;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "status_code:".$status_code."<br />";
curl_close ($ch);
if($status_code == 200) {
//echo $response;
$fp = fopen("tts.mp3", "w+");
fwrite($fp, $response);
fclose($fp);
echo "<a href='tts.mp3'>TTS재생</a>";
} else {
echo "Error 내용:".$response;
}
?>
JavaScript
JavaScript 기반의 CLOVA Voice API 예제 코드는 다음과 같습니다.
var express = require('express');
var app = express();
var client_id = 'YOUR_CLIENT_ID';
var client_secret = 'YOUR_CLIENT_SECRET';
var fs = require('fs');
app.get('/tts', function(req, res) {
var api_url = 'https://naveropenapi.apigw.ntruss.com/tts-premium/v1/tts';
var request = require('request');
var options = {
url: api_url,
form: { speaker: 'nara', volume: '0', speed: '0', pitch: '0', text: '좋은 하루 되세요', format: 'mp3' },
headers: { 'X-NCP-APIGW-API-KEY-ID': client_id, 'X-NCP-APIGW-API-KEY': client_secret },
};
var writeStream = fs.createWriteStream('./tts1.mp3');
var _req = request.post(options).on('response', function(response) {
console.log(response.statusCode); // 200
console.log(response.headers['content-type']);
});
_req.pipe(writeStream); // file로 출력
_req.pipe(res); // 브라우저로 출력
});
app.listen(3000, function() {
console.log('http://127.0.0.1:3000/tts app listening on port 3000!');
});
C#
C# 기반의 CLOVA Voice API 예제 코드는 다음과 같습니다.
using System;
using System.Net;
using System.Text;
using System.IO;
namespace NaverAPI_Guide
{
public class APIExamTTS
{
static void Main(string[] args)
{
string text = "좋은 하루 되세요."; // 음성합성할 문자값
string url = "https://naveropenapi.apigw.ntruss.com/tts-premium/v1/tts";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("X-NCP-APIGW-API-KEY-ID", "YOUR-CLIENT-ID");
request.Headers.Add("X-NCP-APIGW-API-KEY", "YOUR-CLIENT-SECRET");
request.Method = "POST";
byte[] byteDataParams = Encoding.UTF8.GetBytes("speaker=nara&volume=0&speed=0&pitch=0&format=mp3&text=" + text);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteDataParams.Length;
Stream st = request.GetRequestStream();
st.Write(byteDataParams, 0, byteDataParams.Length);
st.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string status = response.StatusCode.ToString();
Console.WriteLine("status="+ status);
using (Stream output = File.OpenWrite("c:/tts.mp3"))
using (Stream input = response.GetResponseStream())
{
input.CopyTo(output);
}
Console.WriteLine("c:/tts.mp3 was created");
}
}
}
이 문서가 도움이 되었습니까?