From f40e835567d0695305876e0b8472039dc2b1654d Mon Sep 17 00:00:00 2001 From: Nathan King Date: Mon, 16 Jan 2023 11:52:14 +0000 Subject: [PATCH] add talking duck js, step 3 --- 02-talking-duck/index.html | 4 +-- 02-talking-duck/script.js | 50 ++++++++++++++++++++++++++++++++++++++ 02-talking-duck/style.css | 15 ++++++++++++ 3 files changed, 67 insertions(+), 2 deletions(-) diff --git a/02-talking-duck/index.html b/02-talking-duck/index.html index a7e473e..ead655d 100644 --- a/02-talking-duck/index.html +++ b/02-talking-duck/index.html @@ -51,8 +51,8 @@
- Static Duck - Animated Duck + Static Duck +
diff --git a/02-talking-duck/script.js b/02-talking-duck/script.js index e69de29..0076fb7 100644 --- a/02-talking-duck/script.js +++ b/02-talking-duck/script.js @@ -0,0 +1,50 @@ +// query the page for elements +const textArea = document.querySelector('textarea') +const playButton = document.querySelector('button') +const pitchBar = document.querySelector('input') +const duckFigure = document.querySelector('figure') + + +// Control what happens when button is clicked +// When clicked, check if there is text in the input field +playButton.addEventListener('click', function () { + const textLength = textArea.value.trim().length + if (textLength > 0) { + speak() + } +}) + +// Function to make the duck talk! +function speak() { + // Retrieve text and audio values + const text = textArea.value + const pitch = pitchBar.value + + // Initialiase a new utterance + const utterance = new SpeechSynthesisUtterance(text) + + // utterance.volume = 1 // 0 - 1 + // utterance.rate = 0.5; // 0.1 - 10 + + // set the pitch level + utterance.pitch = pitch // 0 - 2 + + // Make the duck talk + speechSynthesis.speak(utterance) + + // When the duck begins to speak... + utterance.addEventListener('start', function () { + textArea.disabled = true + pitchBar.disabled = true + playButton.disabled = true + duckFigure.classList.add('talking') + }) + + // When the duck has finished... + utterance.addEventListener('end', function () { + textArea.disabled = false + pitchBar.disabled = false + playButton.disabled = false + duckFigure.classList.remove('talking') + }) +} \ No newline at end of file diff --git a/02-talking-duck/style.css b/02-talking-duck/style.css index 6be225a..6638ec7 100644 --- a/02-talking-duck/style.css +++ b/02-talking-duck/style.css @@ -71,6 +71,11 @@ button { height: 56px; background-color: var(--pink); } + +button:disabled { + opacity: 0.6; + background-color: #dedede; +} button img { vertical-align: middle; @@ -90,3 +95,13 @@ label { width: 100%; accent-color: white; } + +/* # TALKING CLASS */ + +.talking .static-duck { + display: none; +} + +.talking .animated-duck { + display: block; +} \ No newline at end of file