Googleスプレッドシートに書かれた日本語や英語のテキストを、選択してメニューから読み上げる機能を作ってみました。
言語を自動で判別し、日本語は日本語で、英語は英語で発音されます。
また、ダイアログを閉じると音声も自動で停止するように工夫しています。
✅ 特徴
- セルを選んでメニューから読み上げ
- 日本語と英語を自動判別
- ダイアログを閉じれば自動で音声も停止
🛠 導入方法(1分)
- スプレッドシートを開く
- 「拡張機能」→「Apps Script」を選択
- 以下のコードを貼り付けて保存
- スプレッドシートを再読み込みすると、上部に「音声」メニューが表示されます
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('音声')
.addItem('選択セルを読み上げる', 'speakSelectedCell')
.addToUi();
}
function speakSelectedCell() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const range = sheet.getActiveRange();
const text = range.getDisplayValue();
const isJapanese = /[\u3040-\u30FF\u4E00-\u9FFF]/.test(text);
const lang = isJapanese ? 'ja-JP' : 'en-US';
const html = `
<html>
<body>
<p>読み上げ中:<b>${text}</b></p>
<script>
const utterance = new SpeechSynthesisUtterance(${JSON.stringify(text)});
utterance.lang = '${lang}';
speechSynthesis.speak(utterance);
window.onunload = () => {
speechSynthesis.cancel();
};
</script>
</body>
</html>
`;
const ui = HtmlService.createHtmlOutput(html).setWidth(300).setHeight(200);
SpreadsheetApp.getUi().showModalDialog(ui, '音声読み上げ');
}
ゆっくりバージョン
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('音声')
.addItem('選択セルを読み上げる', 'speakSelectedCell')
.addToUi();
}
function speakSelectedCell() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const range = sheet.getActiveRange();
const text = range.getDisplayValue();
const isJapanese = /[\u3040-\u30FF\u4E00-\u9FFF]/.test(text);
const lang = isJapanese ? 'ja-JP' : 'en-US';
const html = `
<html>
<body>
<p>読み上げ中:<b>${text}</b></p>
<script>
const utterance = new SpeechSynthesisUtterance(${JSON.stringify(text)});
utterance.lang = '${lang}';
utterance.rate = 0.7; // ★ 読み上げ速度をゆっくりに設定
speechSynthesis.speak(utterance);
window.onunload = () => {
speechSynthesis.cancel();
};
</script>
</body>
</html>
`;
const ui = HtmlService.createHtmlOutput(html).setWidth(300).setHeight(200);
SpreadsheetApp.getUi().showModalDialog(ui, '音声読み上げ');
}
▶ 使い方
- 読み上げたいセルを選択
- 上部メニューの「音声 → 選択セルを読み上げる」をクリック
- 自動で日本語または英語で読み上げが始まります
- ダイアログを閉じると読み上げも止まります