0

I'm using WebSpeech API to allow users speech recognition on my site. I'm using example 3 on this page: https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html.

My code looks like this:

function _google_speech_speak_form($form, &$form_state) {
$modulepath = drupal_get_path('module','google_speech');
$form['textarea'] = array(
    '#type' => 'textfield',
    '#title' => t('Speak It'),
    '#prefix' => '<div id="api">',
    '#suffix' => '</div>',
   );
$form['button'] = array(
    '#type' => 'button',
    '#attributes' => array('onclick' => 'return (false);'),
    '#value' => t('Click to Speak'),
   );
$form['submitt'] = array(
    '#type' => 'button',
    '#value' => t('Save'),
   );
$form['#after_build'] = array('_google_speech_speak_after_build');
return $form;}

function _google_speech_speak_form_submit($form, &$form_state) {
$speechkey = $form_state['values']['textarea'];
drupal_set_message($speechkey);
echo "test";}


function _google_speech_speak_after_build($form, &$form_state) {
drupal_add_js(drupal_get_path('module', 'google_speech').'/webspeech.js');
return $form;}

Webspeech.js:

 Drupal.behaviors.[google_speech] = function(context) {
 $('#edit-button').click(function() {
  var recognizing;
 var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
reset();
recognition.onend = reset;

recognition.onresult = function (event) {
  for (var i = resultIndex; i < event.results.length; ++i) {
    if (event.results.final) {
      textarea.value += event.results[i][0].transcript;
    }
  }
}

function reset() {
  recognizing = false;
  button.innerHTML = "Click to Speak";
}

function toggleStartStop() {
  if (recognizing) {
    recognition.stop();
    reset();
  } else {
    recognition.start();
    recognizing = true;
    button.innerHTML = "Click to Stop";
  }
  }
 });
 };

I referred to this question: How to make form buttons call only javascript? The "toggle" button is not refreshing the page (which is good) but it's also not toggling speech recognition like it should. There are no errors on the screen or in the logs. Any ideas?

1 Answer 1

0

To properly add JS or CSS to a form you use the #attached array key. See this similar question answered already here with links to documentation. Then your JS button should work.

https://drupal.stackexchange.com/a/70036/3279

1
  • This doesn't resolve the real issue here: the form is being submitted when the "button" is clicked. This refreshes the page and negates the script toggle action. Commented Nov 27, 2013 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.