js实现英文发音
使用Web Speech API实现英文发音
Web Speech API是浏览器原生支持的语音合成接口,无需额外依赖库。以下为基本实现方法:

// 创建语音合成对象
const synth = window.speechSynthesis;
// 获取所有可用语音(可能需要等待voiceschanged事件)
const voices = synth.getVoices();
// 选择英文语音(通常包含'en-US'或'en-GB'等标识)
const englishVoice = voices.find(voice =>
voice.lang.includes('en') && voice.default
);
// 发音函数
function speak(text) {
if (synth.speaking) synth.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.voice = englishVoice;
utterance.rate = 1; // 语速0.1-10
utterance.pitch = 1; // 音高0-2
synth.speak(utterance);
}
// 使用示例
speak("Hello world");
使用第三方库howler.js
howler.js提供更高级的音频控制功能,适合需要预加载发音的场景:

// 安装:npm install howler
import { Howl } from 'howler';
const sound = new Howl({
src: ['https://example.com/audio/hello.mp3'],
preload: true,
volume: 0.8
});
sound.play();
动态生成语音文件
通过API生成语音文件后播放:
async function fetchAndPlay(text) {
const response = await fetch(`https://api.voicerss.org/?key=YOUR_KEY&hl=en-us&src=${encodeURIComponent(text)}`);
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
}
fetchAndPlay("This is dynamically generated speech");
语音参数调整关键属性
const utterance = new SpeechSynthesisUtterance();
utterance.text = "Adjustable speech";
utterance.lang = 'en-US'; // 语言设置
utterance.rate = 0.8; // 慢速
utterance.pitch = 1.5; // 高音调
utterance.volume = 0.7; // 音量
兼容性处理方案
function checkCompatibility() {
if (!('speechSynthesis' in window)) {
console.error('Web Speech API not supported');
return false;
}
return true;
}
function speakWithFallback(text) {
if (checkCompatibility()) {
speak(text);
} else {
// 使用替代方案如音频文件播放
console.warn('Using fallback audio');
new Audio('fallback.mp3').play();
}
}
语音队列管理
const speechQueue = [];
let isSpeaking = false;
function queueSpeech(text) {
speechQueue.push(text);
if (!isSpeaking) processQueue();
}
function processQueue() {
if (speechQueue.length === 0) {
isSpeaking = false;
return;
}
isSpeaking = true;
const text = speechQueue.shift();
const utterance = new SpeechSynthesisUtterance(text);
utterance.onend = () => processQueue();
speechSynthesis.speak(utterance);
}
以上方法可根据具体需求组合使用,Web Speech API适合简单场景,第三方服务适合需要更高音质的场景。注意浏览器权限要求,某些功能需要用户交互后才能触发。



