请查看以下代码
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 url2 = "http://www.translate.google.com/translate_tts?tl=sp&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/mp3" />
</audio>
<div><button onclick="longText()">Click me</button></div>
</body>
然而,这有时会产生以下错误。
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
我想要做的是,如果发生此错误,我想在var url2
中使用var url
代替function longSentenceSpeak(text)
。我怎么能这样做?
更新
我尝试了以下,没有好的
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 url2 = "http://www.translate.google.com/translate_tts?tl=sp&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
audio.onerror = function()
{
var url2 = "http://translate.google.com/translate_tts?tl=en&q="+text;
var audio = document.getElementById('audio');
var source = document.getElementById('source');
source.src = url2;
audio.load(); //call this to just preload the audio without playing
audio.play(); //call this to play the song right away
};
}