使用python播放mp3音频文件

1. pygame

安装

pip3 install pygame
sudo apt-get install libsdl2-mixer-2.0-0 libsdl2-image-2.0-0 libsdl2-2.0-0 libsdl2-ttf-2.0-0 
sudo sdl-config --cflags --libs

此文涉及如何使用脚本获取设备列表。其中一个脚本仅适用于pygame 2.0.0, 另外一个适用于最新的pygame 2.1.2

import pygame as mixer
import pygame._sdl2 as sdl2

mixer.init() # Initialize the mixer, this will allow the next command to work
print(sdl2.audio.get_audio_device_names(False)) # set to False to return playback(output) devices, set to True to return record(input) devices.
mixer.quit() # Quit the mixer as it's initialized on your main playback device

答主的设备列表:

['Speakers (High Definition Audio Device)', 'CABLE Input (VB-Audio Virtual Cable)']

我从脚本获得的设备列表:
使用python播放mp3音频文件_第1张图片

也可以用cat /proc/asound/modules或者aplay -l或者aplay -L 或者cat /proc/asound/cards 来获得设备列表。
aplay -l仅返回alsa检测到的硬件列表,而aplay -L则包含了~/.asoundrc里面自定义的PCM设备名称。

但是上述几种方式获得的设备名称表达方式各有不同,似乎pygame.mixter仅仅支持类似脚本这样获得的名称。
And to set the output audio device for pygame mixer:

import pygame as mixer
import time

mixer.init(devicename = 'Speakers (High Definition Audio Device)') # Initialize it with the correct device
mixer.music.load("Toby Fox - Megalovania.mp3") # Load the mp3
mixer.music.play() # Play it

while mixer.music.get_busy():  # wait for music to finish playing
    time.sleep(1)

但是pygame似乎只支持硬件列表里面的设备?
这个帖子使用~/.asroundrc设定来切换pygame.mixer的默认输出设备。类似的这篇博文使用同样的方式指定pygame.mixer使用USB声卡(card 1)输出。

2. playsound

pip install playsound

ModuleNotFoundError: No module named 'gi' - 解决办法 sudo apt install python3-gi

playsound is relying on another python subprocess. Please use `pip install pygobject` if you want playsound to run more efficiently.
Traceback (most recent call last):
  File "/home/pi/.pyenv/versions/playsound/lib/python3.7/site-packages/playsound.py", line 261, in <module>
    playsound(argv[1])
  File "/home/pi/.pyenv/versions/playsound/lib/python3.7/site-packages/playsound.py", line 163, in _playsoundNix
    gi.require_version('Gst', '1.0')
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 129, in require_version
    raise ValueError('Namespace %s not available' % namespace)
ValueError: Namespace Gst not available
Traceback (most recent call last):

解决办法:pip install pygobject ??
sudo apt install python3-gst-1.0
但是根据这个issue的回复来看,playsound在树莓派上不工作,或者仅在有Gnome的Linux上工作,这意味着纯命令行的Raspbian上不工作。

3. sounddevice

3.1 安装

sudo apt-get install libportaudio2
pip install soundfile
pip install numpy
pip install sounddevice

3.2 支持格式

sounddevice调用了libsndfile1,它不支持mp3格式,但是支持ogg压缩格式。
获取支持格式列表:

from __future__ import print_function
import soundfile as sf

print("PySoundFile version: {}".format(sf.__version__))

for key,val in sf.available_formats().items():
	print("{:5s} -- desc: {}".format(key, val))

返回内容:

$ python formats.py
PySoundFile version: 0.10.3
AIFF  -- desc: AIFF (Apple/SGI)
AU    -- desc: AU (Sun/NeXT)
AVR   -- desc: AVR (Audio Visual Research)
CAF   -- desc: CAF (Apple Core Audio File)
FLAC  -- desc: FLAC (Free Lossless Audio Codec)
HTK   -- desc: HTK (HMM Tool Kit)
SVX   -- desc: IFF (Amiga IFF/SVX8/SV16)
MAT4  -- desc: MAT4 (GNU Octave 2.0 / Matlab 4.2)
MAT5  -- desc: MAT5 (GNU Octave 2.1 / Matlab 5.0)
MPC2K -- desc: MPC (Akai MPC 2k)
OGG   -- desc: OGG (OGG Container format)
PAF   -- desc: PAF (Ensoniq PARIS)
PVF   -- desc: PVF (Portable Voice Format)
RAW   -- desc: RAW (header-less)
RF64  -- desc: RF64 (RIFF 64)
SD2   -- desc: SD2 (Sound Designer II)
SDS   -- desc: SDS (Midi Sample Dump Standard)
IRCAM -- desc: SF (Berkeley/IRCAM/CARL)
VOC   -- desc: VOC (Creative Labs)
W64   -- desc: W64 (SoundFoundry WAVE 64)
WAV   -- desc: WAV (Microsoft)
NIST  -- desc: WAV (NIST Sphere)
WAVEX -- desc: WAVEX (Microsoft)
WVE   -- desc: WVE (Psion Series 3)
XI    -- desc: XI (FastTracker 2)

3.3 获取设备列表

3.3.1 方法1:

import sounddevice
devs = sounddevice.query_devices()
print(devs) # Shows current output and input as well with "<" abd ">" tokens
for dev in devs:
    print(dev['name'])

3.3.2 方法2:

python3 -m sounddevice

上述两种方法都可以返回设备列表,关键是设备现在可选:

$ python getdevice.py
  0 bcm2835 HDMI 1: - (hw:0,0), ALSA (0 in, 8 out)
  1 sysdefault, ALSA (0 in, 128 out)
  2 bluealsa, ALSA (0 in, 128 out)
  3 IN糖, ALSA (0 in, 128 out)
  4 方糖R, ALSA (0 in, 128 out)
  5 dmix, ALSA (0 in, 2 out)
< 6 default, ALSA (0 in, 128 out)
bcm2835 HDMI 1: - (hw:0,0)
sysdefault
bluealsa
IN糖
方糖R
dmix
default

然后使用sounddevice.play()播放,You can either use the device ID (e.g. device=3) or a substring of the device name (e.g. device=‘headphone’, if that’s part of the device name)

import sounddevice as sd
sd.default.samplerate = 44100
sd.default.device = 'digital output'
# sd.default.device = 4
sd.play(myarray)
# Import libraries
import sounddevice as sd
import soundfile as sf
# Extract data and sampling rate from file
array, smp_rt = sf.read(path_of_file, dtype = 'float32')
# start the playback
sd.play(array, smp_rt)
# Wait until file is done playing
status = sd.wait()
# stop the sound
sd.stop()

参考资料:

  1. Play audio with Python - Stack Overflow – 回答涉及 playsound , Simpleaudio 以及 pygame
  2. pygame - Why does my Python code only play sound through my Bluetooth speaker in the IDE, but not the console? - Stack Overflow
  3. Playing sounds with Python on a Raspberry Pi | Jeff Geerling
  4. python 3.x - pygame No available audio device - Stack Overflow
  5. python - Set output device for pygame mixer - Stack Overflow – 回答涉及如何获取pygame的音频设备列表
  6. pygame 的声音播放
  7. pygame.mixer — pygame v2.1.1 documentation
  8. USB card as my default Audio Device - Raspberry Pi Stack Exchange
  9. How to change audio output device for Python? - Raspberry Pi Stack Exchange
  10. pygame.mixer.init Example
  11. Example Programs — python-sounddevice, version 0.4.4-9-gf4607b3
  12. How to Play and Record Audio in Python? - GeeksforGeeks
  13. Playing and Recording Sound in Python – Real Python
    涉及如下软件:
  • Playing Audio Files :playsound, simpleaudio, winsound, python-sounddevice, pydub, pyaudio
  • Recording Audio: python-sounddevice, pyaudio
  • Saving and Converting Audio: wavio, soundfile, pydub
  1. How to Play Sound in Python – 涉及 playsound,pydub, tksnack,simpleaudio,
  2. ubuntu - Error Python PlaySound No module named ‘gi’ - Stack Overflow
  3. No module named ‘gi’ · Issue #24 · TaylorSMarks/playsound
  4. Attempting to use on Rasberry Pi 3: ValueError: Namespace Gst not available · Issue #16 · TaylorSMarks/playsound

你可能感兴趣的:(python,pygame,开发语言)