我看到很久以前有人问过这个问题,但是我遇到了类似的问题,并且我能够使其适用于 Chrome 和 Firefox,但使用了音频标签。
这是我制作的演示页面
http://jsfiddle.net/royriojas/SE6ET/
这是对我有用的代码...
var sayIt;
function createSayIt() {
// Tiny trick to make the request to google actually work!, they deny the request if it comes from a page but somehow it works when the function is inside this iframe!
//create an iframe without setting the src attribute
var iframe = document.createElement('iframe');
// don't know if the attribute is required, but it was on the codepen page where this code worked, so I just put this here. Might be not needed.
iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-pointer-lock');
// hide the iframe... cause you know, it is ugly letting iframes be visible around...
iframe.setAttribute('class', 'hidden-iframe')
// append it to the body
document.body.appendChild(iframe);
// obtain a reference to the contentWindow
var v = iframe.contentWindow;
// parse the sayIt function in this contentWindow scope
// Yeah, I know eval is evil, but its evilness fixed this issue...
v.eval("function sayIt(query, language, cb) { var audio = new Audio(); audio.src = 'http://translate.google.com/translate_tts?ie=utf-8&tl=' + language + '&q=' + encodeURIComponent(query); cb && audio.addEventListener('ended', cb); audio.play();}");
// export it under sayIt variable
sayIt = v.sayIt;
}
我想我能够绕过这个限制。我不知道他们将来可能会修复这个黑客。其实我希望他们不要...
也可以尝试使用Text2Speech HTML5 api,不过还很年轻……
IE 11 不适用于此 hack,未来某个时候我可能会尝试修复它