Windows機でテキストを読み上げさせる(3.5回目)
3回目で使った
winsdk
は廃止されるので、代替のモジュールを使う。
必要なモジュールをインストールする:
pip install winrt-Windows.System winrt-Windows.Storage winrt-Windows.Storage.Streams winrt-Windows.Foundation winrt-Windows.Media winrt-Windows.Media.Core winrt-Windows.Media.Playback winrt-Windows.Media.SpeechSynthesis
そして、実行する:
import asyncio
from winrt.windows.media.core import MediaSource, MediaSourceState
from winrt.windows.media.playback import MediaPlayer
from winrt.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):
player = MediaPlayer()
player.source = MediaSource.create_from_stream(stream, stream.content_type)
player.play()
while player.current_state != MediaSourceState.CLOSED: await asyncio.sleep(.5)
stream = asyncio.run(synthesize_text('13番線に停車中の列車は、17時30分発、寝台特急、北斗星1号、札幌行きです'))
print(stream, stream.size, stream.content_type)
asyncio.run(play(stream))
print('done')
2025/02/23 09:34