0

всем привет. Как можно сделать озвучку каждого символа при наборе в input,textarea

1 ответ 1

2

Если не использовать сторонние API или прeдзаписанные звуки, то можно воспользоваться встроенным во многие браузеры WebSpeechAPI.

Поддерживается множество языков, в том числе и русский.

Вот создал небольшой компонент для удобства, можете его использовать.

class HTMLSpellInputElement extends HTMLElement {
 
  #synth = window.speechSynthesis;
  #volume = 100; 
  #mode = 'tts';
  #lang = 'ru-RU';
  #voices = null;
  
  #input = document.createElement('input');
  
  #hostAttributes = [
    'volume', 'lang', 'mode'
  ];
  
  constructor() {
    super();
    
    this.shadow = this.attachShadow({ mode: 'open' });
    
    for(const attr of this.attributes) {
      if (this.#hostAttributes.includes(attr.name)) {
        this[attr.name] = attr.value;
        continue;
      }
      this.#input.setAttribute(attr.name, attr.value);
    }
    
    this.shadowRoot.append(this.#input);
    
    if (!this.#synth) throw new Error('Speech Synthesis is not supported in your browser');
    
    this.addEventListener('keyup', (event) => {
      const toSpeak = this.#mode === 'spell' ? event.key : this.#input.value;
      
      if (!this.#voices) {
        this.#populateVoiceList().then(() => {
          this.#spell(toSpeak);   
        });
        return;
      }
      
      this.#spell(toSpeak);
    });
    
  }
  
  set lang(lang) {
    this.#lang = lang;
    this.setAttribute('lang', lang);
  }
  
  set mode(mode) {
    this.#mode = mode;
    this.setAttribute('mode', mode);
  }
  
  set volume(volume) {
    try {
      volume = parseInt(volume);
      if (isNaN(volume)) throw new TypeError('Volume value is not a number.');
      if (volume > 100 || volume < 0) {
        this.#volume = 0;
        throw new TypeError('The set volume value is out if  0-100 range. ');
      }
      this.#volume = volume;
      this.setAttribute('volume', volume);
    } catch(err) {
      console.warn(err);
    }
  }
  
  #populateVoiceList() {
    return new Promise((resolve, reject) => {
      if (this.#synth.getVoices()) {
        resolve(this.#synth.getVoices());
      } else {
        reject('Reject in promise: setSpeech()');
      }
    }).then((voices) => {
      this.#voices = voices;
    }).catch(console.error);
  }
  
  #spell(char) {
    if (!char) return;  
    
    const utter = new SpeechSynthesisUtterance(char);
    
    for(const voice of this.#voices) {
      if (voice.lang !== this.#lang) continue;    
      utter.voice = voice;
      break;
    }
    
    utter.pitch = 1
    utter.rate = 1;
    utter.volume = this.#volume;
    
    this.#synth.speak(utter);
  }
}

customElements.define('spell-input', HTMLSpellInputElement);
<div>
  <label for="en">EN</label>
  <spell-input name="en" type="text" lang="en-US" mode="spell" volume="100" placeholder="Начните печатать"></spell-input>
</div>
<hr>
<div>
  <label for="ru">RU</label>
  <spell-input name="ru" type="text" lang="ru-RU" mode="spell" volume="100" placeholder="Начните печатать"></spell-input>
</div>

Полезный материал по WebSpeechAPI:

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.