[javascript] Draft.js를 이용한 텍스트 에디터의 음성인식 기능 구현하기

이번 글에서는 Draft.js를 사용하여 텍스트 에디터에 음성인식 기능을 구현하는 방법을 알아보겠습니다.

1. 음성인식 API 선택하기

첫 번째로 우리는 어떤 음성인식 API를 사용할지 결정해야 합니다. 음성인식 API는 여러 가지가 있지만, Web Speech API를 사용하여 구현해 보도록 하겠습니다.

Web Speech API는 브라우저 기반의 음성인식과 음성 합성 기능을 제공합니다. 또한 크로스 브라우징을 지원하기 때문에 대부분의 최신 브라우저에서 사용할 수 있습니다.

2. Draft.js 설정하기

Draft.js를 사용하여 텍스트 에디터를 생성합니다. Draft.js는 React 기반의 라이브러리로, npm을 사용하여 설치해야 합니다.

import React, { Component } from 'react';
import { Editor, EditorState } from 'draft-js';

class TextEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  onChange = (editorState) => {
    this.setState({ editorState });
  }

  render() {
    return (
      <div>
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
      </div>
    );
  }
}

export default TextEditor;

위의 코드는 Draft.js를 사용하여 간단한 텍스트 에디터를 생성하는 예시입니다. Editor 컴포넌트는 editorState prop을 통해 현재 텍스트 에디터의 상태를 받아오고, onChange prop을 통해 에디터 상태의 변화를 감지하여 editorState를 업데이트합니다.

3. 음성인식 기능 추가하기

이제 Draft.js 에디터에 음성인식 기능을 추가해 보겠습니다. componentDidMount 메서드를 사용하여 브라우저가 음성인식 API를 지원하는지 확인하고, 음성인식 기능을 초기화할 수 있습니다.

componentDidMount() {
  if ('webkitSpeechRecognition' in window) {
    const recognition = new window.webkitSpeechRecognition();
    recognition.continuous = true;
    recognition.interimResults = true;
    recognition.lang = 'en-US';

    recognition.onstart = () => {
      console.log('음성인식이 시작되었습니다.');
    }

    recognition.onresult = (event) => {
      const transcript = event.results[event.results.length - 1][0].transcript;
      console.log(`음성인식 결과: ${transcript}`);
      // 텍스트 에디터에 음성인식 결과를 추가하는 로직 구현
    }

    recognition.onerror = (event) => {
      console.error('음성인식 중 오류가 발생했습니다.', event.error);
    }

    recognition.onend = () => {
      console.log('음성인식이 종료되었습니다.');
    }

    recognition.start();
  } else {
    console.error('이 브라우저에서는 음성인식을 지원하지 않습니다.');
  }
}

위의 코드에서 webkitSpeechRecognition 객체를 생성하고 초기 설정을 한 후, onresult 이벤트 핸들러에서 음성인식 결과를 받아와 텍스트 에디터에 추가하는 로직을 구현하면 됩니다.

4. 텍스트 에디터 업데이트하기

음성인식 결과를 텍스트 에디터에 추가하는 로직은 실제로는 각자의 요구사항에 따라 다를 수 있습니다. 예를 들어, 에디터 컴포넌트의 onChange 메서드를 호출하여 텍스트를 추가하거나, Draft.js의 컨텐트 변환 메서드를 사용하여 텍스트를 업데이트할 수도 있습니다.

import { convertFromRaw, convertToRaw } from 'draft-js';

// ...

recognition.onresult = (event) => {
  const transcript = event.results[event.results.length - 1][0].transcript;
  console.log(`음성인식 결과: ${transcript}`);
  
  // 방법 1: onChange 메서드 호출
  const newContentState = this.state.editorState.getCurrentContent().createTextContent(transcript);
  const newEditorState = EditorState.push(this.state.editorState, newContentState, 'insert-characters');
  this.onChange(newEditorState);

  // 방법 2: Draft.js 컨텐트 변환 메서드 사용
  const contentState = convertToRaw(this.state.editorState.getCurrentContent());
  const newContentState = convertFromRaw({
    ...contentState,
    blocks: [...contentState.blocks, {
      text: `${transcript}\n`,
      type: 'unstyled',
      depth: 0,
      inlineStyleRanges: [],
      entityRanges: [],
      data: {},
    }]
  });
  const newEditorState = EditorState.createWithContent(newContentState);
  this.onChange(newEditorState);
}

위의 코드는 onChange 메서드를 호출하여 새로운 editorState를 설정하는 방법과, Draft.js의 컨텐트 변환 메서드를 사용하여 새로운 텍스트를 추가하는 방법 두 가지를 보여줍니다.

5. 마무리

위에서는 Draft.js를 사용하여 텍스트 에디터에 음성인식 기능을 구현하는 방법을 알아보았습니다. 음성인식 API를 사용하여 사용자의 음성을 텍스트로 변환하고, 해당 텍스트를 텍스트 에디터에 추가하는 방법을 알아보았습니다. 실제로 사용되는 제품에 적용하기 위해서는 이 예시를 참고하여 자신의 요구사항에 맞게 구현해야 합니다.

더 자세한 내용은 Draft.js 공식 문서Web Speech API 문서를 참고하시기 바랍니다.