我尝试使用Windows Media Player通过COM播放音频文件.以下代码在VBS中可以正常工作:Set wmp = CreateObject(WMPlayer.OCX)wmp.settings.autoStart = Truewmp.settings.volume = 50wmp.URL = C:\Windows\Media...

我尝试使用Windows Media Player通过COM播放音频文件.
以下代码在VBS中可以正常工作:
Set wmp = CreateObject("WMPlayer.OCX")
wmp.settings.autoStart = True
wmp.settings.volume = 50
wmp.URL = "C:\Windows\Media\tada.wav"
while wmp.Playstate <> 1
WSH.Sleep 100
wend
不幸的是,相同的代码在Python中无法播放任何声音:
import win32com.client
import time
wmp = win32com.client.dynamic.Dispatch("WMPlayer.OCX")
wmp.settings.autoStart = True
wmp.settings.volume = 50
wmp.URL = r"C:\Windows\Media\tada.wav"
while wmp.Playstate != 1:
time.sleep(0.1)
COM交互似乎很困难,因为我可以创建新的媒体对象并查询有关它们的信息.只是没有声音能听见.
>>> media = wmp.newMedia(r"C:\Windows\Media\tada.wav")
>>> media.durationString
'00:01'
>>> wmp.currentMedia = media
>>> wmp.play() # No sound audible.
>>> wmp.PlayState
9 # wmppsTransitioning
无论我做什么,PlayState始终报告为wmppsTransitioning.
在最后两个PyWin32版本(218和219)中,Python2.7、3.2和3.3会出现问题.操作系统是Windows 7 x64,Python解释器全部编译为32位. WMPlayer.OCX可以成功加载并且COM可以工作,所以我认为这不是32位/ 64位DLL问题.
知道为什么它可以与VBS一起使用而不与Python一起使用吗?我该如何进一步调试呢?
解决方法:
似乎问题在于time.sleep不会发送窗口消息.使用其他一些超时功能来抽取窗口消息.
原因是Windows Media Player是STA组件,很可能是因为它最常用作图形组件.其某些内部功能取决于常规消息泵送,最有可能是发送窗口消息进行通信的高精度多媒体计时器线程,或者可能取决于实际的WM_TIMER消息.
本文标题为:Windows Media Player COM自动化可从VBS运行,但不能从Python运行


基础教程推荐
- python-无法在Windows 7中删除测试文件夹 2023-11-12
- 用Python每天自动给女友免费发短信 2023-08-09
- 【已解决】Python中json.loads出错:ValueError: Expecting , delimiter: line 1 column 86 (char 86) – 在路上 2023-09-04
- 像命令行模拟器一样使用python子进程模块 2023-11-13
- 将串行通信(Ubuntu,Python)发送到Arduino 2023-11-12
- Python多任务之进程 2023-11-13
- python-将代码包装在函数中是否可以获得内存效率? 2023-11-10
- 如何在Python中通过管道传递Python进程的输出? 2023-11-14
- Python之多进程(multiprocessing)学习【3】:平常状态,多线程,多进程比较 2023-11-14
- WindowsError:[错误2]系统找不到指定的文件,无法在Python中解析 2023-11-11