Как установить gtts на python
Перейти к содержимому

Как установить gtts на python

  • автор:

Как самостоятельно преобразовывать текст в речь? [закрыт]

Закрыт. На этот вопрос невозможно дать объективный ответ. Ответы на него в данный момент не принимаются.

Хотите улучшить этот вопрос? Переформулируйте вопрос так, чтобы на него можно было дать ответ, основанный на фактах и цитатах.

Закрыт 2 года назад .

Проблема такая, что у меня есть проект по созданию голосового помощника. Хочу присобачить к нему голос не из интернета, а свой. Возник вопрос, как это сделать? Можете посоветовать литературу по этой теме? Пишу на Python/C++

Отслеживать
задан 2 авг 2021 в 11:54
dytrage gyh dytrage gyh
29 3 3 бронзовых знака

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

Ключевое слово для Вас — TTS (Text To Speach). Собственно, открываем гугли ищем. И тут же находим https://www.geeksforgeeks.org/convert-text-speech-python/

устанавливаем пакет pip install gTTS

# Импортируем нужный модуль # для преобразования from gtts import gTTS # Если есть модуль, можно играть сконвертированное аудио import os # Текст, который нужно преобразовать/произнести mytext = 'Welcome to geeksforgeeks!' # Указываем нужный язык language = 'en' # Передаем текст и язык в движок TTS # добавляя slow=False, что говорит # что модуль должен сконвертировать аудио # с высокой скоростью myobj = gTTS(text=mytext, lang=language, slow=False) # сохраним результат в mp3 myobj.save("welcome.mp3") # воспроизведем плеером os.system("mpg321 welcome.mp3") 

но если хочется совсем свой, то тут все немного сложнее

gTTS 1.2.2

**gTTS** (_Google Text to Speech_): a *Python* interface for Google’s _Text to Speech_ API. Create an _mp3_ file with the `gTTS` module or `gtts-cli` command line utility. It allows unlimited lengths to be spoken by tokenizing long sentences where the speech would naturally pause.

[![Build Status](https://travis-ci.org/pndurette/gTTS.svg?branch=master)](https://travis-ci.org/pndurette/gTTS)
[![PyPI version](https://badge.fury.io/py/gTTS.svg)](https://badge.fury.io/py/gTTS)

You may either use `gTTS` as a **__python module__** or as a **__command-line utility__**

##### 2. Create an instance

«`
>> tts = gTTS(text=’Hello’, lang=’en’, slow=True)
«`

###### _Parameters:_
* `text` — String — Text to be spoken.
* `lang` — String — [ISO 639-1 language code](#lang_list) (supported by the Google _Text to Speech_ API) to speak in.
* `slow` — Boolean — Speak slowly. Default `False` (Note: only two speeds are provided by the API).

##### 3. Write to a file

* _To disk_ using `save(file_name)`

* _To a file pointer_ using `write_to_fp(file_object)`

### B. Command line utility

##### Command
«`
gtts-cli.py [-h] ([«text to speak»] | -f FILE) [-l LANG] [—slow] [—debug] [-o destination_file]
«`

«`
$ # Read the string ‘Hello’ in English to hello.mp3
$ gtts-cli «Hello» -l ‘en’ -o hello.mp3

$ # Read the string ‘Hello’ in English (slow speed) to hello.mp3
$ gtts-cli «Hello» -l ‘en’ -o hello.mp3 —slow

$ # Read the contents of file ‘hello.txt’ in Czech to hello.mp3:
$ gtts-cli -f hello.txt -l ‘cs’ -o hello.mp3

$ # Read the string ‘Hello’ from stdin in English to hello.mp3
$ echo «Hello» | gtts-cli -l ‘en’ -o hello.mp3 —
«`

* ‘af’ : ‘Afrikaans’
* ‘sq’ : ‘Albanian’
* ‘ar’ : ‘Arabic’
* ‘hy’ : ‘Armenian’
* ‘bn’ : ‘Bengali’
* ‘ca’ : ‘Catalan’
* ‘zh’ : ‘Chinese’
* ‘zh-cn’ : ‘Chinese (Mandarin/China)’
* ‘zh-tw’ : ‘Chinese (Mandarin/Taiwan)’
* ‘zh-yue’ : ‘Chinese (Cantonese)’
* ‘hr’ : ‘Croatian’
* ‘cs’ : ‘Czech’
* ‘da’ : ‘Danish’
* ‘nl’ : ‘Dutch’
* ‘en’ : ‘English’
* ‘en-au’ : ‘English (Australia)’
* ‘en-uk’ : ‘English (United Kingdom)’
* ‘en-us’ : ‘English (United States)’
* ‘eo’ : ‘Esperanto’
* ‘fi’ : ‘Finnish’
* ‘fr’ : ‘French’
* ‘de’ : ‘German’
* ‘el’ : ‘Greek’
* ‘hi’ : ‘Hindi’
* ‘hu’ : ‘Hungarian’
* ‘is’ : ‘Icelandic’
* ‘id’ : ‘Indonesian’
* ‘it’ : ‘Italian’
* ‘ja’ : ‘Japanese’
* ‘km’ : ‘Khmer (Cambodian)’
* ‘ko’ : ‘Korean’
* ‘la’ : ‘Latin’
* ‘lv’ : ‘Latvian’
* ‘mk’ : ‘Macedonian’
* ‘no’ : ‘Norwegian’
* ‘pl’ : ‘Polish’
* ‘pt’ : ‘Portuguese’
* ‘ro’ : ‘Romanian’
* ‘ru’ : ‘Russian’
* ‘sr’ : ‘Serbian’
* ‘si’ : ‘Sinhala’
* ‘sk’ : ‘Slovak’
* ‘es’ : ‘Spanish’
* ‘es-es’ : ‘Spanish (Spain)’
* ‘es-us’ : ‘Spanish (United States)’
* ‘sw’ : ‘Swahili’
* ‘sv’ : ‘Swedish’
* ‘ta’ : ‘Tamil’
* ‘th’ : ‘Thai’
* ‘tr’ : ‘Turkish’
* ‘uk’ : ‘Ukrainian’
* ‘vi’ : ‘Vietnamese’
* ‘cy’ : ‘Welsh’

gTTS

gTTS (Google Text-to-Speech), a Python library and CLI tool to interface with Google Translate’s text-to-speech API. Write spoken mp3 data to a file, a file-like object (bytestring) for further audio manipulation, or stdout . https://gtts.readthedocs.io/

Features

  • Customizable speech-specific sentence tokenizer that allows for unlimited lengths of text to be read, all while keeping proper intonation, abbreviations, decimals and more;
  • Customizable text pre-processors which can, for example, provide pronunciation corrections;

Installation

$ pip install gTTS 

Quickstart

$ gtts-cli 'hello' --output hello.mp3 
>>> from gtts import gTTS >>> tts = gTTS('hello') >>> tts.save('hello.mp3') 

See https://gtts.readthedocs.io/ for documentation and examples.

Disclaimer

This project is not affiliated with Google or Google Cloud. Breaking upstream changes can occur without notice. This project is leveraging the undocumented Google Translate speech functionality and is different from Google Cloud Text-to-Speech.

Project

  • Questions & community
  • Changelog
  • Contributing

Licence

The MIT License (MIT) Copyright © 2014-2024 Pierre Nicolas Durette & Contributors

Python — получаем звук из текста

звук из текста

звук из текста

На помощь приходит библиотека gtts, документация по которой доступна по ссылке (вопрос установки библиотеки в компьютер не рассматриваем �� ).

Итак, у нас имеется задача: есть текст, на выходе нужно получить аудиофайл. Решается эта задача очень просто:

from gtts import gTTS #Подключили библиотеку
ru = str('Добрый день!') #Задали текст на русском языке
de = str('Guten tag!') #Задали текст на немецком языке (в качестве примера)
tts_ru = gTTS(ru, lang='ru') #Обозначили язык нашего текста
tts_de = gTTS(de, lang='de') #Обозначили язык нашего текста
with open('hello.mp3', 'wb') as f: #Создали файл в который будем писать звук из текста
tts_ru.write_to_fp(f) #Записываем в файл озвучку русского текста
tts_de.write_to_fp(f) #Записываем в файл озвучку немецкого текста

Видео с примером кода:

На этом тема получения звук из текста с помощью Python закрыта. Спасибо за внимание! В случае возникновения вопросов — пишите на почту или в Telegram.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *