[我正在编写一个简单的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)
这不是我想要的,我希望能够在不保存的情况下播放音频,我该怎么做。
如果您对外部库开放,则可以使用vlc
为python安装pip install python-vlc
绑定>
并使用播放器方法直接从以下内容播放音频。
import vlc import time 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