2015-01-21 175 views
1

我正在尝试使用Google翻译网址服务进行TTS。HTML5音频出错

以下是代码的JavaScript代码。

function longSentenceSpeak(text) 
{ 
    var string = text.trim().split(" ").join("+"); 
    var finalString = string.replace(";",",") 
    var url = "http://www.translate.google.com/translate_tts?tl=en&q="+finalString; 

    var audio = document.getElementById('audio'); 

    var source = document.getElementById('source'); 
    source.src=url; 

    audio.load(); //call this to just preload the audio without playing 
    audio.play(); //call this to play the song right away 
} 

下面是我的HTML

TODO供应标题

<script src="scripts/TTS.js"></script> 
    <script> 
     function longText() 
     { 
      longSentenceSpeak("hello world "); 
     } 
    </script> 
</head> 
<body> 
    <audio id="audio"> 
     <source id="source" src="" type="audio/wav" /> 
    </audio> 

    <div><button onclick="longText()">Click me</button></div> 
</body> 

然而,这根本就不行,好像HTML 5音频无法处理URL。当我运行这个代码时,我得到了下面的错误。

Failed to load resource: the server responded with a status of 404 (Not Found) (12:49:15:455 | error, network) 
    at http://www.translate.google.com/translate_tts?tl=en&q=hello 

但我敢肯定的URL是正确的,因为你可以试试这个

http://www.translate.google.com/translate_tts?tl=en&q=hello%20world

下面是JS小提琴链接

http://jsfiddle.net/f1hgk5sc/

我做了什么错这里?

+0

我居然得到了一个错误:http://i.imgur.com/k94RKFV.png,有时它的工作,有时这一点。 – jdphenix 2015-01-21 07:39:16

回答

1

那么我只是复制你的代码,一切都很好。

function longSentenceSpeak(text) { 
 
    var string = text.trim().split(" ").join("+"); 
 
    var finalString = string.replace(";", ",") 
 
    var url = "http://www.translate.google.com/translate_tts?tl=en&q=" + finalString; 
 

 
    var audio = document.getElementById('audio'); 
 

 
    var source = document.getElementById('source'); 
 
    source.src = url; 
 

 
    audio.load(); //call this to just preload the audio without playing 
 
    audio.play(); //call this to play the song right away 
 
}
<html> 
 

 
<head> 
 
    <script> 
 
    function longText() { 
 
     longSentenceSpeak("hello world "); 
 
    } 
 
    </script> 
 
</head> 
 

 
<body> 
 
    <audio id="audio"> 
 
    <source id="source" src="" type="audio/wav" /> 
 
    </audio> 
 

 
    <div> 
 
    <button onclick="longText()">Click me</button> 
 
    </div> 
 
</body> 
 

 
</html>

+0

没有声音..给出错误'加载资源失败:服务器响应状态为404(未找到)(14:45:09:044 |错误,网络) at http://www.translate .google.com/translate_tts?tl = en&q = hello + world – 2015-01-21 09:13:20

+0

您使用哪个网页浏览器? – Glapa 2015-01-21 09:58:44

+0

Google Chrome .. – 2015-01-21 10:26:39