PYTHON2DAY Telegram 6286
🎧 Генерируем аудиокнигу из текста с помощью Python!

Хотите создать аудиокнигу, озвучку статей или озвучить текст на другом языке? Всё просто — используем Python и gTTS!

Что умеет этот скрипт?
Конвертирует текст в речь и сохраняет в MP3.
Поддерживает разные языки(английский, русский, французский и т.д.)
Можно настроить скорость речи;
Автоматически воспроизводит файл после создания.

import os
from gtts import gTTS

def create_audiobook(text_file: str, output_file: str, lang: str = 'en', speed: bool = False) -> None:
"""
Конвертирует текст из файла в аудиофайл.

:param text_file: Путь к текстовому файлу.
:param output_file: Название выходного аудиофайла.
:param lang: Язык синтеза речи (по умолчанию английский).
:param speed: Скорость речи (False = нормальная, True = медленная).
"""
try:
with open(text_file, 'r', encoding='utf-8') as file:
text = file.read()

tts = gTTS(text=text, lang=lang, slow=speed)
tts.save(output_file)

print(f" Аудиокнига сохранена как {output_file}")

# Автоматически воспроизводим аудиофайл после создания (только для Windows)
if os.name == 'nt':
os.system(f"start {output_file}")
elif os.name == 'posix': # Для MacOS и Linux
os.system(f"xdg-open {output_file}")

except FileNotFoundError:
print(" Ошибка: Указанный файл не найден.")
except Exception as e:
print(f"⚠️ Произошла ошибка: {e}")

if __name__ == "__main__":
text_file = "example.txt" # Замените на ваш файл
output_file = "audiobook.mp3"

# Вызываем функцию с указанием языка (например, 'ru' для русского)
create_audiobook(text_file, output_file, lang='ru', speed=False)


📂 Сохраняем 👍

#python #soft #code #cheatsheet
Please open Telegram to view this post
VIEW IN TELEGRAM
👍77🔥276



tgoop.com/python2day/6286
Create:
Last Update:

🎧 Генерируем аудиокнигу из текста с помощью Python!

Хотите создать аудиокнигу, озвучку статей или озвучить текст на другом языке? Всё просто — используем Python и gTTS!

Что умеет этот скрипт?
Конвертирует текст в речь и сохраняет в MP3.
Поддерживает разные языки(английский, русский, французский и т.д.)
Можно настроить скорость речи;
Автоматически воспроизводит файл после создания.

import os
from gtts import gTTS

def create_audiobook(text_file: str, output_file: str, lang: str = 'en', speed: bool = False) -> None:
"""
Конвертирует текст из файла в аудиофайл.

:param text_file: Путь к текстовому файлу.
:param output_file: Название выходного аудиофайла.
:param lang: Язык синтеза речи (по умолчанию английский).
:param speed: Скорость речи (False = нормальная, True = медленная).
"""
try:
with open(text_file, 'r', encoding='utf-8') as file:
text = file.read()

tts = gTTS(text=text, lang=lang, slow=speed)
tts.save(output_file)

print(f" Аудиокнига сохранена как {output_file}")

# Автоматически воспроизводим аудиофайл после создания (только для Windows)
if os.name == 'nt':
os.system(f"start {output_file}")
elif os.name == 'posix': # Для MacOS и Linux
os.system(f"xdg-open {output_file}")

except FileNotFoundError:
print(" Ошибка: Указанный файл не найден.")
except Exception as e:
print(f"⚠️ Произошла ошибка: {e}")

if __name__ == "__main__":
text_file = "example.txt" # Замените на ваш файл
output_file = "audiobook.mp3"

# Вызываем функцию с указанием языка (например, 'ru' для русского)
create_audiobook(text_file, output_file, lang='ru', speed=False)


📂 Сохраняем 👍

#python #soft #code #cheatsheet

BY [PYTHON:TODAY]




Share with your friend now:
tgoop.com/python2day/6286

View MORE
Open in Telegram


Telegram News

Date: |

While the character limit is 255, try to fit into 200 characters. This way, users will be able to take in your text fast and efficiently. Reveal the essence of your channel and provide contact information. For example, you can add a bot name, link to your pricing plans, etc. The public channel had more than 109,000 subscribers, Judge Hui said. Ng had the power to remove or amend the messages in the channel, but he “allowed them to exist.” In 2018, Telegram’s audience reached 200 million people, with 500,000 new users joining the messenger every day. It was launched for iOS on 14 August 2013 and Android on 20 October 2013. 6How to manage your Telegram channel? Telegram users themselves will be able to flag and report potentially false content.
from us


Telegram [PYTHON:TODAY]
FROM American