>  기사  >  웹 프론트엔드  >  네이티브 텍스트를 음성으로 반응

네이티브 텍스트를 음성으로 반응

WBOY
WBOY원래의
2024-08-31 06:31:36360검색

React Native Text To Speech

React-native-tts 살펴보기: React Native의 텍스트 음성 변환에 대한 종합 가이드

텍스트 음성 변환(TTS) 기술은 작성된 텍스트를 음성으로 변환하여 모바일 애플리케이션과 상호 작용하는 방식을 변화시키고 있습니다. React Native 애플리케이션을 개발 중이고 TTS 기능을 통합하려는 경우, React-native-tts는 이러한 통합을 간단하게 만들어주는 널리 사용되는 라이브러리입니다. 이 가이드에서는 설치, 기본 사용법 및 고급 기능을 다루면서 React-native-tts를 사용하는 방법을 살펴보겠습니다.


반응 네이티브 tts 란 무엇입니까?

react-native-tts는 개발자가 앱에 음성 합성 기능을 추가할 수 있게 해주는 React Native용 텍스트 음성 변환 라이브러리입니다. Android와 iOS를 모두 지원하므로 크로스 플랫폼 개발을 위한 다양한 선택이 가능합니다. React-native-tts를 사용하면 텍스트를 음성으로 변환하고, 피치 및 속도와 같은 음성 매개변수를 제어하고, 다양한 음성 이벤트를 처리할 수 있습니다.


설치

react-native-tts를 시작하려면 npm 또는 Yarn을 통해 설치해야 합니다. 터미널을 열고 다음을 실행하세요.

npm install react-native-tts

또는

yarn add react-native-tts

용법

a) ttsListeners.jsx 파일을 생성합니다:

import Tts from 'react-native-tts';

// Function to initialize Text-to-Speech (TTS) settings and listeners
export const initializeTtsListeners = async () => {
  // Check the initialization status of the TTS engine
  Tts.getInitStatus().then(
    (e) => {
      console.log('ALL OK TTS ✅'); // TTS is initialized successfully
    },
    (err) => {
      // If there is no TTS engine installed, request to install one
      if (err.code === 'no_engine') {
        console.log('NO ENGINE TTS ✅');
        Tts.requestInstallEngine();
      }
    }
  );

  // The following commented-out code can be used to list available voices and set a default voice
  // const voices = await Tts.voices()
  // console.log(voices)
  // Tts.setDefaultVoice('com.apple.speech.synthesis.voice.Albert')

  // Set the default speaking rate. Lower values are slower, and higher values are faster
  Tts.setDefaultRate(0.3, true);

  // Ignore the silent switch on the device, allowing TTS to play even if the device is set to silent
  Tts.setIgnoreSilentSwitch('ignore');

  // Set the default pitch. Lower values result in a lower pitch, and higher values in a higher pitch
  Tts.setDefaultPitch(0.7);

  // Set up listeners for various TTS events

  // Listener for when TTS starts speaking
  Tts.addEventListener('tts-start', (event) => {
    console.log('TTS Started: ', event);
  });

  // Listener for TTS progress (triggered repeatedly while speaking)
  Tts.addEventListener('tts-progress', (event) => {
    // console.log('TTS progress: ', event) // Uncomment to log progress events
  });

  // Listener for when TTS finishes speaking
  Tts.addEventListener('tts-finish', (event) => {
    console.log('TTS finished: ', event);
  });

  // Listener for when TTS is canceled
  Tts.addEventListener('tts-cancel', (event) => {
    console.log('TTS Cancel: ', event);
  });
};

// Function to play a message using TTS
export const playTTS = async (message) => {
  // Ensure TTS is initialized before speaking
  Tts.getInitStatus().then(
    (e) => {
      console.log('ALL OK TTS ✅'); // TTS is initialized successfully
    },
    (err) => {
      // If there is no TTS engine installed, request to install one
      if (err.code === 'no_engine') {
        console.log('NO ENGINE TTS ✅');
        Tts.requestInstallEngine();
      }
    }
  );

  // Use TTS to speak the provided message
  Tts.speak(message);
};

b) 이제 초기화하고 사용하세요.

App.jsx

import { StyleSheet, Text, View } from 'react-native';
import React from 'react';
import { initializeTtsListeners } from './utils/ttsListners';

const App = () => {
  useEffect(() => {
    initializeTtsListeners();

    setTimeout(() => {
      playTTS('Hello World! This is text to speech implementation, Keep Coding!!!.'); // or Tts.speak(message)

    }, 1000);
  }, []);

  return (
    <View>
      <Text>App</Text>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({});

결론

react-native-tts는 React Native 애플리케이션에 텍스트 음성 변환 기능을 추가하기 위한 강력하고 유연한 라이브러리입니다. 쉬운 설정, 이벤트 처리 및 고급 기능을 통해 자연어 상호 작용을 통합하여 사용자 경험을 향상시킬 수 있습니다. 다양한 구성을 실험하고 TTS를 최대한 활용하여 매력적이고 접근 가능한 애플리케이션을 만드세요.

위 내용은 네이티브 텍스트를 음성으로 반응의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.