반응형
기본 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Speech Detection</title>
</head>
<body>
<div class="words" contenteditable>
</div>
<script>
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
</script>
<style>
html {
font-size: 10px;
}
body {
background:#ffc600;
font-family: 'helvetica neue';
font-weight: 200;
font-size: 20px;
}
.words {
max-width:500px;
margin:50px auto;
background:white;
border-radius:5px;
box-shadow:10px 10px 0 rgba(0,0,0,0.1);
padding:1rem 2rem 1rem 5rem;
background: -webkit-gradient(linear, 0 0, 0 100%, from(#d9eaf3), color-stop(4%, #fff)) 0 4px;
background-size: 100% 3rem;
position: relative;
line-height:3rem;
}
p {
margin: 0 0 3rem;
}
.words:before {
content: '';
position: absolute;
width: 4px;
top: 0;
left: 30px;
bottom: 0;
border: 1px solid;
border-color: transparent #efe4e4;
}
</style>
</body>
</html>
목표
웹 API를 사용하여 음성인식과 동시에 화면에 출력이 가능하도록 만들어 보자.
코드 분석
const recognition = new SpeechRecognition();
recognition.interimResults = true;
let p = document.createElement('p');
const words = document.querySelector('.words');
words.appendChild(p);
recognition.addEventListener('result', e => {
const transcript = Array.from(e.results)
.map(result => result[0])
.map(result => result.transcript)
.join('');
const poopScript = transcript.replace(/poop|poo|shit|dump/gi, '💩');
p.textContent = poopScript;
if (e.results[0].isFinal) {
p = document.createElement('p');
words.appendChild(p);
}
});
recognition.addEventListener('end', recognition.start);
recognition.start();
위에서부터 살펴보자, interimResults
는 웹 API 중 음성인식에 관련된 부분이다.
그 다음, 이벤트 리스너 부분을 보면 transcript
에 이벤트의 결과들을 배열로 집어 넣는 것이다.
그리고 여기에서의 이벤트는 당연하게도 음성인식이 될 것이다.
그렇게 인식한 결과들을 .map
으로 하나의 배열로 만들어주고, .join
으로 배열의 모든 요소들을 하나의 문자열로 만들어준다.
아래의 poopScript
는 .replace
를 사용하여 정해놓은 단어들을 원하는 그림으로 바꾸어 출력하고, 그 출력값을 p
에 넣어주는 것이다.
마지막으로 조건문을 보면, .isFinal
은 끝났는지의 여부를 알려주는 메서드이기 때문에 말하는게 끝났다면, 다음 문단으로 내려주는 조건문이다.
마무리
이번 회차도 웹 API를 이용한 회차라 조금 신기했다.
끝.
반응형
'개발 > JavaScript 30' 카테고리의 다른 글
22. Follow Along Link Highlighter (0) | 2017.04.26 |
---|---|
21. Geolocation (0) | 2017.04.26 |
19. Webcam Fun (0) | 2017.04.24 |
18. Adding Up Times with Reduce (0) | 2017.04.24 |
17. Sort Without Articles (0) | 2017.04.22 |