728x90
반응형

[JavaScript] 자바스크립트로 라이브러리 없이 TTS(Text-To-Speech) 기능 사용하는 방법 !!
브라우저에 내장되어 있는 TTS기능을 불러오는 방식입니다ㅎ
생각보다 성능이 좋아 가볍게 사용하기 좋습니다 !!
예제코드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
font-family: sans-serif;
background-color: #f2f2f2;
}
h1 {
margin-bottom: 2rem;
text-align: center;
color: #444;
}
.form-group {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 1.5rem;
}
label {
margin-bottom: 0.5rem;
color: #666;
}
select,
textarea {
padding: 0.5rem;
border: none;
border-radius: 4px;
font-size: 1rem;
color: #444;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
resize: none;
}
select {
max-width: 200px;
margin-right: 1rem;
}
textarea {
min-width: 300px;
min-height: 100px;
max-width: 500px;
max-height: 200px;
margin-bottom: 0.5rem;
}
.btn-read {
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
font-size: 1rem;
color: #fff;
background-color: #007aff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
cursor: pointer;
transition: all 0.2s ease-in-out;
}
.btn-read:hover {
background-color: #0057b8;
}
</style>
<body>
<div class="form-group">
<label for="select-lang">언어 선택:</label>
<select id="select-lang">
<option value="ko-KR">한국어</option>
<option value="en-US">영어</option>
</select>
</div>
<div class="form-group">
<label for="text">변환할 텍스트:</label>
<textarea id="text"></textarea>
</div>
<button class="btn-read" id="btn-read">읽기</button>
</body>
</html>
<script>
function speak(text, opt_prop) {
if (typeof SpeechSynthesisUtterance === "undefined" || typeof window.speechSynthesis === "undefined") {
alert("이 브라우저는 음성 합성을 지원하지 않습니다.")
return
}
window.speechSynthesis.cancel() // 현재 읽고있다면 초기화
const prop = opt_prop || {}
const speechMsg = new SpeechSynthesisUtterance()
speechMsg.rate = prop.rate || 1 // 속도: 0.1 ~ 10
speechMsg.pitch = prop.pitch || 1 // 음높이: 0 ~ 2
speechMsg.lang = prop.lang || "ko-KR"
speechMsg.text = text
// SpeechSynthesisUtterance에 저장된 내용을 바탕으로 음성합성 실행
window.speechSynthesis.speak(speechMsg)
}
// 이벤트 영역
const selectLang = document.getElementById("select-lang")
const text = document.getElementById("text")
const btnRead = document.getElementById("btn-read")
btnRead.addEventListener("click", e => {
speak(text.value, {
rate: 1,
pitch: 1.2,
lang: selectLang.options[selectLang.selectedIndex].value
})
})
</script>
결과값
728x90
반응형
'Coding > JavaScript' 카테고리의 다른 글
[JavaScript] 자바스크립트로 브라우저 크기 변경 및 사이즈 확인 하는 방법 !! (0) | 2023.04.18 |
---|---|
[JavaScript] 자바스크립트로 가위 바위 보 게임 만들기 !! (0) | 2023.04.16 |
[JavaScript] 자바스크립트로 div 태그안에 있는 내용 삭제 하는 방법 !! (0) | 2023.04.05 |
[JavaScript] 자바스크립트로 STT API(Web Speech API) 사용하기 !! (0) | 2023.03.25 |
[JavaScript] 자바스크립트로 input 태그에 휴대전화번호 하이픈(-) 넣는 방법 !! (0) | 2023.03.17 |
댓글