Python 播放音效 簡易版

Kiwi lee
3 min readSep 18, 2020

概述

想要在 Ubuntu18, Python3.6 的程式中,放出聲音音效。以下找了幾種方法,按照需求選擇,不一定我最後選擇的就是最好的。

  1. playsound
  2. pyAudio
  3. pyGame
  4. cvlc

方法

playsound

>>> from playsound import playsound
>>> playsound('/path-to-file/play.mp3', block=True)
  • Debug:中間有遇到 gi 套件錯誤,直接 pip 安裝相關套件
$ pip install vext
$ pip install vext.gi
  • 使用心得:
    很簡單的使用。在 windows, OS 可以允許 non-block 播放,但 linux 沒辦法使用。有嘗試用新的 thread/process 來執行,但很像都卡住了,所以就放棄了。

PyAdudio

PyGame

  • 安裝方法: pip install pygame
  • 範例程式:
import pygamepygame.init()
pygame.mixer.init()
pygame.mixer.music.load('/path-to-file/play.mp3')
pygame.mixer.music.play()
  • 使用心得:
    不會像 playsound 卡住 main-thread。但啟動時,有些許延遲,再改了些設定後,調整 buffer ,還是沒辦法修正,放棄。

調整 mixier buffer: https://stackoverflow.com/questions/18273722/pygame-sound-delay

cvlc

  • 簡介: vlc 的無視窗版本,屬於 應用程式
  • 安裝方法: sudo apt install vlc-nox
  • 範例指令:播放完關閉
$ cvlc --play-and-exit /path-to-file/play.mp3
  • 使用方法:使用 subprocess 來啟動,透過 poll() 來確定是否有音效正在播放,若有,則透過 terminate() 來關閉
sound_proc = subprocess.Popen('cvlc --play-and-exit /path-to-file/play.mp3', shell=True)# early shutdown
if sound_proc.poll() is None:
self.sound_process.terminate()
  • 使用心得:
    雖然不是用 python module ,但這個方法可以完成我要的需求。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Access the best member-only stories.

Support independent authors.

Listen to audio narrations.

Read offline.

Join the Partner Program and earn for your writing.

Kiwi lee

Hi, I'm kiwi, Platform Engineer (SRE, DevOps). Python Engineer https://kiwilee-blog.netlify.app/