tts.js 1.72 KB
import AWS from 'aws-sdk'
// Polly를 사용하기 위한 자격증명을 설정한다.
AWS.config.region = 'ap-northeast-2'; 
AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'ap-northeast-2:03db97c9-a857-45f3-be6e-3cf84d6f619b'});
const polly = new AWS.Polly({
    signatureVersion: 'v4',
    region: 'ap-northeast-2',
});

const audioQueue = []
// test data
// const audioQueue = ["https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"]

const audio = new Audio()

// queue에서 작업(재생할 내용)을 0.5초마다 폴링하는 방식
function enableAudio(){
    setInterval(()=>{
        // 앞선 tts 재생이 종료된 경우에만 새 tts를 실행
        if( !audio.paused){ return;}

        let audioFile = audioQueue.shift()
        // 재생할 게 있으면 재생
        if (audioFile){
            console.log(audioFile)
            audio.setAttribute("src", audioFile)
            audio.play()
        }
    }, 500)
}

function enqueueTTS(text){
    let params = {
        'Text': text,
        'OutputFormat': 'mp3',
        'VoiceId': 'Seoyeon'
    };
    let tts = new AWS.Polly.Presigner(params, polly)

    // tts로 변환한 음성 파일을 얻는다.
    tts.getSynthesizeSpeechUrl(params, function(error, url) {
        if (error) {
        } else {
            audioQueue.push(url)
        }
    })
}

console.log("테스트용 TTS 데이터를 주입합니다.")
enqueueTTS("복잡한 브랜치")
enqueueTTS("빵상 아주머니는 말씀하셨다.")
enqueueTTS("니가가라 하와이")

export default {
    enableAudio,
    enqueueTTS,    
}