音声入力をテキストに変換してWEBカメラに表示 Javascript
2025年1月2日
index.php
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice to Text</title>
<style>
.container { position:relative; }
.container video {
position:relative;
z-index:0;
}
.output {
position:absolute;
bottom: 10px;
left: 20px;
z-index:1;
color: white;
font-size: 24px;
font-weight: bold;
width: 600px;
}
button,option {background-color: #008CBA; color: white;} /* Blue */
</style>
</head>
<body>
<div class="container">
<video id="video" width="640" height="480" autoplay></video>
<div id="output" class="output" contentEditable="true"></div>
</div>
<button id="startButton">音声入力スタート</button>
<button id="clear">テキストクリア</button>
<script>
var video = document.getElementById("video");
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.srcObject = stream;
video.play();
});
}
// Reference to the elements
const startButton = document.getElementById("startButton");
const outputDiv = document.getElementById("output");
const clearButton = document.getElementById("clear");
// Constants for the language and the default language
const LANG = "ja-JP";
// Event listeners for the clear button
clearButton.addEventListener("click", () => {
outputDiv.textContent = "";
});
// Create a new SpeechRecognition object
const recognition = new (window.SpeechRecognition ||
window.webkitSpeechRecognition ||
window.mozSpeechRecognition ||
window.msSpeechRecognition)();
// Set the language of the recognition
recognition.lang = LANG;
// Event listeners for the recognition
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
outputDiv.textContent += ` ${transcript}`;
};
// Event listeners for the start and end of the recognition
recognition.onstart = () => startButton.textContent = "Listening...";;
recognition.onend = () => startButton.textContent = "Start Voice Input";;
startButton.addEventListener("click", () => recognition.start());
function onLanguageChange() {
recognition.lang = document.getElementById("language").value;
}
</script>
</body>
</html>