js-speech-by-text hi0a.com
view source
JavaScript
/*
ブラウザは SpeechSynthesisUtterance の音声を MediaStreamDestination に直接送れない
*/
// 音声のURLができたときに呼び出す関数
function renderAudioPlayer(blobUrl) {
// 音声プレイヤー作成
const audio = document.createElement("audio");
audio.controls = true;
audio.src = blobUrl;
// ダウンロードリンク作成
const link = document.createElement("a");
link.href = blobUrl;
link.download = "speech.webm"; // 必要に応じて拡張子を.mp3などに
link.textContent = "音声をダウンロード";
// 埋め込み先に追加(任意の要素IDに)
const container = document.getElementById("demo");
container.innerHTML = ""; // 既存の内容を消す場合
container.appendChild(audio);
container.appendChild(document.createElement("br"));
container.appendChild(link);
}
//renderAudioPlayer()
function readyArea(){
const container = document.getElementById("demo");
// テキストエリア
const textarea = document.createElement("textarea");
textarea.id = "text";
textarea.rows = 4;
textarea.cols = 50;
textarea.value = "こんにちは、世界!";
// ボタン
const button = document.createElement("button");
button.textContent = "音声合成して録音";
button.onclick = speakAndRecord; // 既存関数をそのまま使う
// オーディオプレイヤー
const audio = document.createElement("audio");
audio.id = "audio";
audio.preload = "none";
audio.controls = true;
// 要素を順に追加
container.appendChild(textarea);
container.appendChild(document.createElement("br"));
container.appendChild(button);
container.appendChild(document.createElement("br"));
container.appendChild(audio);
}
readyArea();
async function speakAndRecord() {
const text = document.getElementById("text").value;
const utterance = new SpeechSynthesisUtterance(text);
const synth = window.speechSynthesis;
const audioContext = new AudioContext();
const destination = audioContext.createMediaStreamDestination();
const recorder = new MediaRecorder(destination.stream);
const source = audioContext.createMediaStreamSource(destination.stream);
const chunks = [];
recorder.ondataavailable = e => chunks.push(e.data);
recorder.onstop = e => {
const blob = new Blob(chunks, { type: "audio/webm" });
const url = URL.createObjectURL(blob);
document.getElementById("audio").src = url;
// ダウンロードリンク作成
const a = document.createElement("a");
a.href = url;
a.download = "speech.webm";
a.textContent = "音声をダウンロード";
document.body.appendChild(a);
};
// Workaround: speech → speakers (not routed to AudioContext directly)
// Use a hidden iframe with audio output device, or use Web Speech API to .speak then re-record via mic or system audio (not ideal).
// 代替案:音声ファイルを事前生成 or サーバー側で処理
// 開始
recorder.start();
synth.speak(utterance);
// 推定終了タイミング(粗い)
utterance.onend = () => {
recorder.stop();
};
}
CSS
HTML
ページのソースを表示 : Ctrl+U , DevTools : F12
view-source:https://hi0a.com/demo/-js/js-speech-by-text/
ABOUT
hi0a.com 「ひまあそび」は無料で遊べるミニゲームや便利ツールを公開しています。
プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。
必要な機能の関数をコピペ利用したり勉強に活用できます。
プログラムの動作サンプル結果は画面上部に出力表示されています。
環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。
画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。
仕様変更、API廃止等、実験途中で動かないページもあります。