我正在编写一个简单的python程序,该程序获取文本文件,然后使用IBM Watson 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)
那不是我想要的,我希望能够在不保存的情况下播放音频,我该怎么做。
答案 0 :(得分:1)
如果您愿意使用外部库,则可以使用vlc
pip install 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