Google Cloud Text-to-Speechを利用して、React音声読み上げ機能を実装してみました。
※事前にGoogle Cloud Text-to-Speechを利用できるようにしておきます。API Keyも発行しておきます。
※割と雑な記事ですみません。
1. Reactアプリ作成
mkdir speech
cd speech
npx create-react-app .
2. コード実装(src/App.js)
import React, { useState } from 'react';
function base64ToBlob(base64Data, contentType) {
const byteCharacters = atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function App() {
const [text, setText] = useState('');
const [audioUrl, setAudioUrl] = useState('');
const handleTextChange = (e) => {
setText(e.target.value);
};
const handleTextToSpeech = async () => {
const response = await fetch('https://texttospeech.googleapis.com/v1/text:synthesize?key=XXXXXXXXXXXXXXXXXX', { # ご自身のAPI-Keyを入れてください。
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
input: {
text: text,
},
voice: {
languageCode: 'ja-JP',
ssmlGender: 'NEUTRAL',
},
audioConfig: {
audioEncoding: 'MP3',
speakingRate: '1.25',
},
}),
});
const data = await response.json();
if (data.audioContent) {
const audioBlob = base64ToBlob(data.audioContent, 'audio/mp3');
const audioUrl = URL.createObjectURL(audioBlob);
setAudioUrl(audioUrl);
}
};
return (
<div>
<textarea value={text} onChange={handleTextChange} />
<button onClick={handleTextToSpeech}>Text to Speech</button>
{audioUrl && <audio src={audioUrl} controls />}
</div>
);
}
export default App;
3. 実行
npm start