2014-05-15 97 views
-1

關於在Python中控制Windows媒體播放器的任何想法?我發現在網上運行良好,但沒有音頻播放下面的代碼。我正在使用win7 64位機器自動化Windows媒體播放器

# this program will play MP3, WMA, MID, WAV files via the WindowsMediaPlayer 
from win32com.client import Dispatch 
mp = Dispatch("WMPlayer.OCX") 
#tune = mp.newMedia("./SleepAway.mp3") 
tune = mp.newMedia("./plays.wav") 
mp.currentPlaylist.appendItem(tune) 
mp.controls.play() 
raw_input("Press Enter to stop playing") 
mp.controls.stop() 
+0

WMP的音量設置? –

+1

這可能與[本週遇到的問題]有關(https://stackoverflow.com/questions/25157138)。關鍵是要確保您在控制線程中抽取Windows消息。 raw_input不這樣做。 –

+0

我對於一個有相同的問題,使用Windows 7和python以編程方式播放聲音...如果你想要看到我的問題,但它永遠不會解決。看起來你可以很好地使用os.startfile,也許可以看看。這裏是我的問題在http://stackoverflow.com/questions/20696948/how-to-do-text-to-speech-with-python-on-a-toshiba-laptop-and-windows-7 –

回答

1

正如我在評論中提到的,我有一個相同的問題。我試過a ridiculous number of different approaches。他們都沒有真正的工作,所以我被困在使用os.startfile來打開Windows媒體播放器播放我的聲音文件。但是,就在今天,我有一個想法,導致了另一種解決方案。這有點破解,但它的工作原理。從技術上講,我仍然使用這種方法打開Windows媒體播放器,但是我使用子進程來進行操作,因此我可以更好地控制該進程所允許的進程來抑制窗口。這使它看起來像沒有輔助應用程序一樣播放。爲什麼我必須做些奇怪的事情才能得到我不知道的簡單結果,但這是唯一奏效的東西。這是我的代碼,如果你想。

import subprocess 
import threading 

def windowsmedia(filename): 
    startupinfo = subprocess.STARTUPINFO() 
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW 
    a = subprocess.call('C:\\Program Files (x86)\\Windows Media Player\\wmplayer.exe /play /close "C:/Users/Student/Documents/notes/file.mp3"',startupinfo=startupinfo) 

def startmp3(filename): 
    mythread = threading.Thread(target=windowsmedia,args=[filename]) 
    mythread.start() 
    time.sleep(15) #You might want to extend this... I just give it 15 seconds to complete before killing the process. It shouldn't be too hard to read the exact length from the file and wait that, or add an interrupt, but that was somewhat unnecessary for my purposes. 
    pkill("wmplayer") #This is a function of my own but it basically just kills the process. It shouldn't be too hard to reproduce. 

同樣它確實令人遺憾的是我必須做的事情如此怪異的只是播放聲音,但只要你描述它,這是同樣的問題,我希望這有助於。

0

想到了,它可能會幫助其他仍然面臨這個問題的人。 您只需在Play()後調用PlayItem()API。

from win32com.client import Dispatch 
from time import sleep 

mp = Dispatch("WMPlayer.OCX") 
tune = mp.newMedia("./plays.wav") 
mp.currentPlaylist.appendItem(tune) 
mp.controls.play() 
sleep(1) 
mp.controls.playItem(tune) 
raw_input("Press Enter to stop playing") 
mp.controls.stop()