Skip to content

Instantly share code, notes, and snippets.

@ALEX7320
Created November 11, 2023 02:54
Show Gist options
  • Save ALEX7320/6725e461259bbc9a71b9111f07be9b7a to your computer and use it in GitHub Desktop.
Save ALEX7320/6725e461259bbc9a71b9111f07be9b7a to your computer and use it in GitHub Desktop.
Convertir texto a voz con win32com.client [Python 3]
# 1. LEER TEXTO / CONFIGURACIONES
# pip install pypiwin32
import win32com.client
speaker=win32com.client.Dispatch("SAPI.SpVoice")
speaker.Rate = -1# rango -10(lento) - 10(rapido)
speaker.Volume = 100# rango 0(vajo) - 100(alto)
speaker.Speak("TEXTO DE PRUEBA")
# 2. CAMBIAR VOZ DE WINDOWS
# pip install pypiwin32
import win32com.client
speaker=win32com.client.Dispatch("SAPI.SpVoice")
##con este obtendremos la voz de nuestro sistema
##en donde dice 'Item(0)' solo cambiamos el numero 0
##esta cantidad pedendera de cuantas voces tengas en el windows
tipo_voz=speaker.GetVoices().Item(1).GetDescription()
print(tipo_voz)
##>>Microsoft Helena Desktop - Spanish (Spain)
##pero solo no sirve hasta antes del "-"
##Para ello recorremos la cadena hast la posicion del "-"
##-1 esto ultimo es por el espacio " " y ese dato no nos sive
tipo_voz=tipo_voz[0:tipo_voz.index("-")-1]
print(tipo_voz)
##>>Microsoft Helena Desktop
##en esta parte seleccionamos la voz
##se puede poner tambien de esta manera
##('Name=Microsoft Helena Desktop').Item(0)
speaker.Voice = speaker.GetVoices('Name='+tipo_voz).Item(0)
##acá puedes poner el VOLUMEN y RATE
speaker.Speak("TEXTO DE PRUEBA")
# 3. OBTENER LISTADO DE VOCES
# pip install pypiwin32
import win32com.client
speaker=win32com.client.Dispatch("SAPI.SpVoice")
'''
WHILE
En este caso no se uso un "for" debido a que el numero de voces
en nuestra computadora es indefinido.
TRY
Usaremos "except" debido a que si el "contador" llega a un rango de
voces que no tengamos, se detenga el while.
LIST
Estas "numeroKEY" "nombreVALUE" se juntaran para transformarlo en un diccionario
te facilitara la seleccion.
'''
numeroKEY=[]##almacena numero
nombreVALUE=[]##almacena el nombre de voz
try:
contador=0##recorre numero de voces
while True:
##contador dentro de Item(contador)
tipo_voz=speaker.GetVoices().Item(contador).GetDescription()
print(tipo_voz)
numeroKEY.append(contador)
nombreVALUE.append(tipo_voz[0:tipo_voz.index("-")-1])
##nuevamente recortamos solo la voz
##>>Microsoft Helena Desktop - Spanish (Spain)##valor real
##>>Microsoft Helena Desktop##pero quedara asi
##este metodo lo explique en el codigo de arriba "2. CAMBIAR VOZ DE WINDOWS" ↑↑↑
contador+=1#por ultimo aumentamos el contador, para recorrer voz
except:pass##en este caso no hay break, el while se detiene x el error
##por ultimo generamos nuestro diccionario
##con el metodo "dict" y "zip"
voxIdiomas=dict(zip(numeroKEY,nombreVALUE))
print("\nvoxIdiomas =",voxIdiomas)
##ACA LO PUEDES ADJUNTAR CON UN PEQUEÑO PROGRAMA
numero_index=int(input("\nSeleccione voz del diccionario: "))
print(voxIdiomas[numero_index])
##quedara de la siguiente manera ej:('Name=Microsoft Zira Desktop')
speaker.Voice = speaker.GetVoices('Name='+voxIdiomas[numero_index]).Item(0)
##acá puedes poner el VOLUMEN y RATE
speaker.Speak("TEXTO DE PRUEBA")
# 4. GENERAR ARCHIVO DE SONIDO (.wav)
# pip install pypiwin32
# pip install comtypes
import win32com.client
import comtypes.client##este es para generar el archivo
speaker=comtypes.client.CreateObject("SAPI.SpVoice")
##--------GENERAR
fileCreate = comtypes.client.CreateObject("SAPI.spFileStream")##creamos archivo
fileCreate.open("archivo_prueba.wav",3, False)##abrimos archivo
speaker.AudioOutputStream = fileCreate
##↑ nos indica que la salida
##el "speaker" saldra en "fileCreate"
##y no en el altavoz
##acá puedes cambiar la VOZ y poner el VOLUMEN y RATE
speaker.Speak("TEXTO DE PRUEBA")##este texto no se leera, solo se guarda
fileCreate.close()##cerramos archivo##--------GENERAR_FIN
# 5. LEER TEXTO DE FONDO
# pip install pypiwin32
# pip install threaded
import win32com.client
from threading import Thread##estos son hilos
import pythoncom##evitar errores de "threading" en "win32com"
##en esta funcion sonara el audio
def de_fondo():
pythoncom.CoInitialize()##para evitar errores
speaker=win32com.client.Dispatch("SAPI.SpVoice")
##acá puedes cambiar la VOZ y poner el VOLUMEN y RATE
speaker.Speak("TEXTO DE PRUEBA")
##ESCRITURA 1
Thread(target=de_fondo).start()
##ESCRITURA 2
'''
variable=Thread(target=de_fondo)##inicializa
variable.start()##entra en accion
'''
print("ACA TUS SIGUIENTES CODIGOS")
for i in range(10):
print("num",i)
# 6. GENERAR ARCHIVO DE FONDO (.wav)
# pip install pypiwin32
# pip install threaded
# pip install comtypes
import win32com.client
import comtypes.client##este es para generar el archivo
from threading import Thread##estos son hilos
import pythoncom##evitar errores de "threading" en "win32com"
##en esta funcion sonara el audio
def de_fondo():
pythoncom.CoInitialize()##para evitar errores
##ACÁ GENERAMOS ARCHIVO
##explicado arriba "4. GENERAR ARCHIVO DE SONIDO (.wav)"
speaker=comtypes.client.CreateObject("SAPI.SpVoice")
fileCreate = comtypes.client.CreateObject("SAPI.spFileStream")
fileCreate.open("archivo_prueba.wav",3, False)
speaker.AudioOutputStream = fileCreate
speaker.Speak("TEXTO DE PRUEBA")
fileCreate.close()
##ESCRITURA 1
Thread(target=de_fondo).start()
##ESCRITURA 2
'''
##tambien puede se de esta manera para indicarle
##donde queremos iniciar la conversion
variable=Thread(target=de_fondo)##inicializa
variable.start()##entra en accion
'''
print("ACA TUS SIGUIENTES CODIGOS")
for i in range(10):
print("num",i)
# 7. TENER EN CUENTA
'''
a la hora de leer o convertir un texto
tenemos que diferenciar cierto parametro
-PARA LECTURA
-nos indica "win32com.client.Dispatch"
speaker=win32com.client.Dispatch("SAPI.SpVoice")
-PARA GENERAR ARCHIVO .wav
-nos indica "comtypes.client.CreateObject"
speaker=comtypes.client.CreateObject("SAPI.SpVoice")
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment