Search code examples
javascriptjqueryhtmlannyang

How to start annyang API to listen after one click on a start botton


I'm not sure if this is a bug. I try to make an even 'onclick' on a start bottom and start listening any word to start the program. But right now is playing the first audio automatically every time when I refresh the page after 3 seconds. Did I do something wrong? Any help would be helpful. Thank you in advance.

<script>                          
    if (annyang) 
    {
        function playFirstAudio()
        {
            audio.src = dir + playList[audioIndex] + extention;
            audio.load();
            setTimeout(function(){audio.play();}, 3000);
        }

        var playList = ["1_hello", "2_how_old", "3_what_did_you_make"];
        var dir = "sound/";
        var extention = ".wav";

        var audioIndex = 0;
        audio = new Audio();

        //annyang.addCallback('start', playFirstAudio);

        audio.onended = playFirstAudio();

        annyang.debug(true);
    };
</script>

<div class="container">
    <button id="runProgram" onclick='annyang.start();' class="runProgrambutton">Start</button>
</div>

Solution

  • You are calling the playFirstAudio() when you are trying to set the audio.ended callback. Note: audio.ended not audio.onended

    audio.onended = playFirstAudio(); //<-- this is calling playFirstAudio();
    

    You assign a call back function by specifying the method name without (), like this:

     audio.onended = playFirstAudio;
    

    Otherwise, wrap it in a anonymous function like this:

     audio.onended = function() { playFirstAudio(); };
    

    Your button click is firing the voice recognition to start.

    But you also need to register a call back to fire when a sound is heard by the voice recognition engine:

    <script>  
        var audio = new Audio();                        
        if (annyang) 
        {
            annyang.addCallback('start', function() {console.log('started listening');});
            annyang.addCallback('soundstart', function {onSoundDetected();});            
    
            function onSoundDetected() {
                console.log('sound was detected');
                playNextAudio();
            }
            var playList = ["sound/1_hello.wav", "sound/2_how_old.wav", "sound/3_what_did_you_make.wav"];
            var audioIndex = 0;
    
            function playNextAudio()
            {
                audio.src = playList[audioIndex++];
                audio.load();
                audioIndex= audioIndex % playList.Length;// start at zero when we reach the end.
    
            }
            audio.ended = function() {playNextAudio()};
            audio.oncanplay = function() {audio.play();}
            annyang.debug(true);
        };
    </script>
    
    <div class="container">
        <button id="runProgram" onclick='annyang.start();' class="runProgrambutton">Start</button>
    </div>