Windows機でテキストを読み上げさせる(3回目)
Windows Runtime APIsを使う
winrtが最新のPythonでインストールできない。
代わりに
Python Windows SDKを使う。
前回のコードを基に、再生の終了まで待つ部分を改良する。
import time
import asyncio
from winsdk.windows.media.core import MediaSource, MediaSourceState
from winsdk.windows.media.playback import MediaPlayer
from winsdk.windows.media.speechsynthesis import SpeechSynthesizer
# 確認用
# for voice in SpeechSynthesizer.get_all_voices(): print('{} / {} / {} / {} / {}'.format(voice.id, voice.display_name, voice.language, voice.description, voice.gender))
# print(SpeechSynthesizer.get_default_voice())
async def synthesize_text(text, voice=None):
synth = SpeechSynthesizer()
if voice is not None: synth.voice = voice
return await synth.synthesize_text_to_stream_async(text)
async def play(stream):
class Control():
async def wait(self, player):
while player.current_state != MediaSourceState.CLOSED: time.sleep(.5)
control = Control()
player = MediaPlayer()
player.source = MediaSource.create_from_stream(stream, stream.content_type)
player.play()
await control.wait(player)
stream = asyncio.run(synthesize_text('13番線に停車中の列車は、17時30分発、寝台特急、北斗星1号、札幌行きです'))
print(stream, stream.size, stream.content_type)
asyncio.run(play(stream))
print('done')
2025/02/21 08:09