1

私の考えは、Googleの「TTS Api」を使用して、任意のテキストをオーディオファイルとして動的に再生するJSを作成することです。これは私の JS コードの一部であり、Chrome でファイルを実行するときに発生するエラーです。どういうわけか、for ループ内の配列内の一部のオーディオ オブジェクトにアクセスできません。

配列text_partには、使用したいテキストが含まれています。配列audioElementListeには、さまざまなオーディオ オブジェクトが含まれています。

私が得るエラー: Uncaught TypeError: Cannot call method 'play' of undefined

ところで、英語は私の母国語ではなく、私はまったくの 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();
    }
4

1 に答える 1