오봉이와 함께하는 개발 블로그
Naver A.I Platform - Text To Speech(TTS) 본문
728x90
CLOVA Voice - Premium (TTS)
음성 합성 API 서비스
텍스트를 음성으로 변환 : TTS(Text-To-Speech)
텍스트 파일을 입력 받아서 변환된 음성 파일(mp3/wav) 반환
언어, 음색 선택 가능
(1) 반환된 데이터를 mp3 파일로 저장
@Service
public class TTSService {
public void clovaTextToSpeech() {
String clientId = "";//애플리케이션 클라이언트 아이디값";
String clientSecret = "";//애플리케이션 클라이언트 시크릿값";
try {
String text = URLEncoder.encode("Hello, nice to meet you", "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=clara&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("/Users/gobyeongchae/Desktop/" + 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);
}
}
}
@RequestMapping("clovaTTS")
public void ttsService() {
ttsService.clovaTextToSpeech();
}
- (2) 파일 업로드 / 결과 mp3파일
@RequestMapping("/clovaTTS")
public String clovaTTS(@RequestParam("uploadFile") MultipartFile file,
@RequestParam("country") String country) {
String tts = "";
try {
// 1. 파일 저장 경로 설정 : 실제 서비스되는 위치 (프로젝트 외부에 저장)
String uploadPath = "/Users/gobyeongchae/Desktop/productImages";
// 2. 원본 파일 이름 알아오기
String originalFileName = file.getOriginalFilename();
String filePathName = uploadPath + originalFileName;
// 3. 파일 생성
File file1 = new File(filePathName);
// 4. 서버로 전송
file.transferTo(file1);
// 서비스에 파일 path와 파일명 전달 -> 서비스 메소드에서 변경
// 서비스에서 반환된 파일명 받아오기
tts = ttsService.clovaTextToSpeech(filePathName, country);
} catch (Exception e) {
e.printStackTrace();
}
return tts;
}
@Service
public class TTSService { // 파일 경로 및 언어 전달 받아서, 저장된 파일명 반환
public String clovaTextToSpeech(String filePathName, String country) {
String clientId = "";//애플리케이션 클라이언트 아이디값";
String clientSecret = "";//애플리케이션 클라이언트 시크릿값";
String voiceFileName = "";
try {
// 전달 받은 파일에서 텍스트를 추출하는 함수
String fileContents = fileRead(filePathName);
String text = URLEncoder.encode(fileContents, "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=" + country + "&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();
voiceFileName = "tts_" + tempname + ".mp3";
File f = new File("/Users/gobyeongchae/Desktop/" + voiceFileName);
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);
}
return voiceFileName;
}
// 파일 경로 전달받아 파일 내용 읽어서 텍스트 반환
public String fileRead(String filePathName) {
String result = "";
try {
File file = new File(filePathName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
result += line;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
return result;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>STT Service2</title>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="js/tts.js"></script>
</head>
<body>
<!-- 파일 업로드 -->
<h3>음석 인식</h3>
<form id="ttsForm" enctype="multipart/form-data">
파일 : <input type="file" id="uploadFile" name="uploadFile">
<br>
<br>
언어 선택 :
<select name="country" id="country">
<option value="nara" selected>한국어, 여성</option>
<option value="jinho">한국어, 남성</option>
<option value="nhajun">한국어, 아동(남)</option>
<option value="ndain">한국어, 아동(여)</option>
<option value="shinji">일본어, 남성</option>
<option value="matt">영어, 남성</option>
<option value="clara">영어, 여성</option>
<option value="carmen">스페인어, 여성</option>
<option value="meimei">중국어, 여성</option>
</select>
<input type="submit" value="결과 확인">
</form>
<br><br>
<!-- 객체와 좌표 값 출력 -->
TTS 결과 : <div id="resultDiv"></div>
<br><br>
<div><audio preload="auto" controls></audio></div>
<a href="/">index 페이지로 이동</a>
</body>
</html>
$(function () {
// submit 했을 때 처리
$('#ttsForm').on('submit', function (event) {
event.preventDefault();
var formData = new FormData($('#ttsForm')[0]);
var fileName = $('#uploadFile').val().split("\\").pop();
$.ajax({
type : "post",
enctype : "multipart/form-data",
url : "clovaTTS",
data : formData,
processData : false, // 필수
contentType : false, // 필수
success:function (result) {
$('audio').prop("src", '/images/' + result);
$('#resultDiv').text(result); // 저장된 음성 파일명
},
error:function (e) {
alert("오류 발생" + e);
}
});
})
})
728x90
'Naver A.I Platform' 카테고리의 다른 글
Naver A.I Platform - Chatbot 서비스(메세지 직접 입력) (0) | 2022.01.26 |
---|---|
Naver A.I Platform - Chatbot 서비스 (0) | 2022.01.26 |
Naver A.I Platform - CLOVA Speech Recognition (CSR : 음성 인식) (0) | 2022.01.25 |
Naver A.I Platform - Object Detection (객체 탐지) (0) | 2022.01.25 |
Naver A.I Platform - Pose Estimation(포즈 인식) (0) | 2022.01.24 |
Comments