I am trying to implement speech transcription using the Web Speech API. I have tried to implement it using custom code, but it does not work. Do you know the cause of this problem?
HTMLコード
<div class="container">
<div class="recording-item">
<img src="https://cdn.weweb.io/designs/2afd96ad-ac24-478b-8f12-0210d86e95fc/sections/material-symbols_circle-outline.svg?_wwcv=1708075412254" id="startRecording" alt="Start" />
</div>
<div class="recording-item">
<div id="loader" class="ww-loader" style="--sk-color: #000; --sk-size: 50px; padding: 12px; display: none;">
<div class="sk-wave">
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
<div class="sk-wave-rect"></div>
</div>
</div>
<p id="isRecording">停止中</p>
</div>
<div class="recording-item">
<img src="https://cdn.weweb.io/designs/2afd96ad-ac24-478b-8f12-0210d86e95fc/sections/material-symbols_circle-outline_(1).svg?_wwcv=1708075456937" id="stopRecording" alt="stop" />
</div>
</div>
<p id="transcription"></p>
<audio src="" id="audioElement" controls></audio>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
.container {
display: flex;
justify-content: space-evenly;
align-items: flex-start;
margin-bottom: 20px;
}
.recording-item {
display: flex;
flex-direction: column;
align-items: center;
}
#startRecording, #stopRecording {
width: 50px;
height: 50px;
cursor: pointer;
}
#isRecording {
font-size: 18px;
margin-top: 10px;
}
#loader {
display: none;
}
#audioElement {
width: 100%;
}
#transcription {
margin-top: 20px;
font-size: 18px;
color: #333;
}
</style>
custom js
document.getElementById("startRecording").addEventListener("click", initFunction);
let isRecording = document.getElementById("isRecording");
let loader = document.getElementById("loader");
let transcription = document.getElementById("transcription");
let recognition;
function initFunction() {
if (!('webkitSpeechRecognition' in window)) {
alert("Web Speech API is not supported in this browser.");
return;
}
isRecording.textContent = "録音中";
loader.style.display = "block";
transcription.textContent = "";
recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = 'ja-JP';
recognition.onresult = (event) => {
let interimTranscript = '';
let finalTranscript = '';
for (let i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
finalTranscript += event.results[i][0].transcript;
} else {
interimTranscript += event.results[i][0].transcript;
}
}
transcription.innerHTML = finalTranscript + '<i style="color:#999;">' + interimTranscript + '</i>';
};
recognition.onend = () => {
isRecording.textContent = "停止中";
loader.style.display = "none";
};
recognition.start();
document.getElementById("stopRecording").addEventListener("click", () => {
recognition.stop();
});
}