오봉이와 함께하는 개발 블로그

Naver A.I Platform - Text To Speech(TTS) 본문

Naver A.I Platform

Naver A.I Platform - Text To Speech(TTS)

오봉봉이 2022. 1. 25. 17:31
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파일