如何在不保存到文件的情况下收听IBM Watson文本到语音结果(python)

2024-05-20 12:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的python程序,它获取一个文本文件,然后使用ibmwatson text-To-Speech将其转换为音频,然后使用playsound等模块直接播放音频。你知道吗

大多数教程只向您展示了如何将结果保存到一个文件中,而不是如何将其传递给一个播放音频的模块

from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
text_to_speech = TextToSpeechV1(
    authenticator=authenticator
)

text_to_speech.set_service_url('{url}')

with open('hello_world.wav', 'wb') as audio_file:
    audio_file.write(
        text_to_speech.synthesize(
            'Hello world',
            voice='en-US_AllisonVoice',
            accept='audio/wav'        
        ).get_result().content)

这不是我想要的,我想能够播放音频而不保存它,我怎么能做到这一点。你知道吗


Tags: 模块totextfromimportauthenticatorurlworld
1条回答
网友
1楼 · 发布于 2024-05-20 12:11:08

如果您是为外部库打开的,那么可以使用pip install python-vlc为python安装vlc绑定

使用播放器方法直接从以下内容播放音频。你知道吗

import vlc
from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
text_to_speech = TextToSpeechV1(
    authenticator=authenticator
)

text_to_speech.set_service_url('{url}')


#define VLC instance
instance = vlc.Instance(' input-repeat=-1', ' fullscreen')

#Define VLC player
player=instance.media_player_new()

#Define VLC media
media=instance.media_new(
text_to_speech.synthesize(
            'Hello world',
            voice='en-US_AllisonVoice',
            accept='audio/wav').get_result().content)

#Set player media
player.set_media(media)

#Play the media
player.play()

vlc播放器的优点是,您可以直接从URL(不仅仅是mp3)播放大多数媒体类型,还可以执行类似播放器的选项,如

>>> play.pause()  #pause play back
>>> player.play() #resume play back
>>> player.stop() #stop play back

*credits

相关问题 更多 >