javascript - TTS HTML5 音频事件监听器

标签 javascript html audio addeventlistener

我的想法是创建一个 JS,它使用 Google“TTS Api”动态地将任何文本作为音频文件播放。这是我的 JS 代码的一部分,以及在 Chrome 中执行该文件时遇到的错误。不知何故,我无法在 for 循环中访问数组中的某些音频对象。

数组text_part包含我想要使用的文本。 数组audioElementListe包含不​​同的音频对象。

我得到的错误: 未捕获的类型错误:无法调用未定义的“play”方法

顺便说一句,英语不是我的母语,我是个 JS 初学者;)

audioElementListe = new Array(3);
function start()
{
    text_part = new Array(3);
    text_part[0]='Hallo';
    text_part[1]='Florian';
    text_part[2]='Haha';

    for(var i = 0; i < text_part.length; i++)
    {   
        audioElementListe[i] = new Audio("");
    }

    for(var i = 0; i < text_part.length; i++)
    {   
            var help = 0;
            var url = "http://translate.google.com/translate_tts?tl=de&q="+text_part[i];
            audioElementListe[i] = new Audio("");
            document.body.appendChild(audioElementListe[i]);
            audioElementListe[i].src=url;
            audioElementListe[i].addEventListener('canPlay', function()                 
            {audioElementListe[i].play();}, false);

            //Error seems to be right here
            audioElementListe[i].addEventListener('ended', function()   
            {audioElementListe[i++].play();}, false);
    }
    audioElementListe[0].play();
}

编辑:通过不创建新的音频对象而是更改其来源来制定“解决方法”。

<html>
<head>
</head>

<body>

<script type="text/javascript">

var audioElement;
var i;
function start()
{   
        i=0;
        text_part = new Array(3);
        text_part[0]='Hallo';
        text_part[1]='Florian';
        text_part[2]='Haha';

        var url = "http://translate.google.com/translate_tts?tl=de&q="+text_part[i];
        audioElement = new Audio("");
        document.body.appendChild(audioElement);
        audioElement.src=url;
        audioElement.addEventListener('canPlay', function() {audioElement.play();}, false);
        audioElement.addEventListener('ended', function()  
        {

                i++;
                if(i<text_part.length)
            {
                var url = "http://translate.google.com/translate_tts?tl=de&q="+text_part[i];
                audioElement.src=url;
                audioElement.addEventListener('canPlay', function() {audioElement.play();}, false);
                audioElement.play();
            }

;}, false);
        audioElement.play();
    }

最佳答案

我们需要将要读取的字符串分成等长的大部分,并引入一个合适的js语句setTimeOut(string, dt)

http://renatocappellani.altervista.org/blog/programmazione-dei-ritardi-in-javascript-settimeoutcomandotempo/

关于javascript - TTS HTML5 音频事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14293274/

相关文章:

javascript - 按某个元素后跟另一个元素对对象数组进行分组

javascript - 困惑 - html5 history api 和谷歌爬虫?

javascript - 优化 Retina 显示的网站图像

javascript - 空并在 html 页面上放置外部 javascript

iphone - 如何通过套接字或框架将音频从 iPhone 的麦克风流式传输到 Mac/PC?

c# - 播放整个声音文件 C# - Visual Studio

javascript - 具有多种功能的jquery插件

javascript - 如何将ajax结果传递给谷歌地图

javascript - Promise.all 消耗了我所有的内存

html - 如何让 Jumbotron 图像随屏幕调整大小?