使用 python 播放聲音,目前找到較佳解法,除了使用 pyQT 之外,最方便的就是 playsound. 很神奇在 Windows 平台會顯示錯誤訊息:
驅動程式無法辨識指令的命令參數
The driver cannot recognize the specified command
解法:
Run this in CMD or any such terminal:
pip install playsound==1.2.2
Downgrading the version works perfectly
先用platform 檢查,如果 Windows 平台,如果又是播放 wav 格式,遇到錯誤是,可以試看看切換到其他的套件來播放音效:
- simpleaudio:播放WAV文件和NumPy數組。
- winsound:播放WAV文件或鳴響您的系統揚聲器
https://docs.python.org/3/library/winsound.html - subprocess
其他解法:Playing mp3 song on python
https://stackoverflow.com/questions/20021457/playing-mp3-song-on-python
Grab the VLC Python module, vlc.py, which provides full support for libVLC and pop that in site-packages. Then:
>>> import vlc
>>> p = vlc.MediaPlayer("file:///path/to/track.mp3")
>>> p.play()
And you can stop it with:
>>> p.stop()
from pygame import mixer # Load the popular external library
mixer.init()
mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3')
mixer.music.play()
subprocess
import subprocess
def play_mp3(path):
subprocess.Popen(['mpg123', '-q', path]).wait()
or
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", "/Users/me/Downloads/sample.wav"])