使用Python播放音频

问题:使用Python播放音频

如何从Python脚本播放音频(听起来像1秒钟的声音)?

最好是独立于平台,但首先需要在Mac上运行。

我知道我可以afplay file.mp3在Python中执行命令,但是可以在原始Python中执行吗?如果它不依赖外部库,我也会更好。

How can I play audio (it would be like a 1 second sound) from a Python script?

It would be best if it was platform independent, but firstly it needs to work on a Mac.

I know I could just execute the afplay file.mp3 command from within Python, but is it possible to do it in raw Python? I would also be better if it didn’t rely on external libraries.


回答 0

您可以在此处找到有关Python音频的信息:http : //wiki.python.org/moin/Audio/

没有外部库,它似乎无法播放.mp3文件。您可以将.mp3文件转换为.wav或其他格式,也可以使用PyMedia之类的库。

You can find information about Python audio here: http://wiki.python.org/moin/Audio/

It doesn’t look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.


回答 1

最好的选择可能是使用pygame / SDL。它是一个外部库,但是在各个平台上都有很好的支持。

pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()

您可以在pygame.mixer.music文档中找到有关音频混音器支持的更多特定文档。

Your best bet is probably to use pygame/SDL. It’s an external library, but it has great support across platforms.

pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()

You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation


回答 2

看一下Simpleaudio,它是一个相对较新的轻量级库,用于此目的:

> pip install simpleaudio

然后:

import simpleaudio as sa

wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()

确保使用未压缩的16位PCM文件。

Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:

> pip install simpleaudio

Then:

import simpleaudio as sa

wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()

Make sure to use uncompressed 16 bit PCM files.


回答 3

试试playsound,它是一个纯Python,跨平台,单一功能的模块,没有依赖于播放声音。

通过pip安装:

$ pip install playsound

安装后,您可以像这样使用它:

from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')

Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.

Install via pip:

$ pip install playsound

Once you’ve installed, you can use it like this:

from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')

回答 4

pydub中,我们最近选择使用ffmpeg工具套件中的ffplay (通过子进程,该套件内部使用SDL。

它可以达到我们的目的-主要是使交互模式下测试pydub代码的结果更容易-但它有缺点,例如导致新程序出现在Mac上的扩展坞中。

我已经链接了上面的实现,但是下面是一个简化的版本:

import subprocess

def play(audio_file_path):
    subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])

-nodisp标志阻止ffplay显示新窗口,并且-autoexit当音频文件播放完毕后,该标志使ffplay退出并返回状态代码。

编辑:pydub现在在安装时使用pyaudio进行播放,并回落到ffplay以避免我提到的缺点。上面的链接也显示了该实现。

In pydub we’ve recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.

It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it’s downsides, like causing a new program to appear in the dock on mac.

I’ve linked the implementation above, but a simplified version follows:

import subprocess

def play(audio_file_path):
    subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])

The -nodisp flag stops ffplay from showing a new window, and the -autoexit flag causes ffplay to exit and return a status code when the audio file is done playing.

edit: pydub now uses pyaudio for playback when it’s installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.


回答 5

抱歉,回复晚,但是我认为这是宣传我的图书馆的好地方…

AFAIK,标准库只有一个用于播放音频的模块:ossaudiodev。可悲的是,这仅适用于Linux和FreeBSD。

更新:还有winsound,但显然这也是特定于平台的。

对于某些与平台无关的东西,您需要使用一个外部库。

我的建议是sounddevice模块(但请注意,我是作者)。

该软件包包括针对Mac OS X和Windows 的预编译的PortAudio库,可以通过以下方式轻松安装:

pip install sounddevice --user

它可以播放NumPy数组中的声音,但也可以使用普通的Python缓冲区(如果NumPy不可用)。

要播放NumPy数组,这就是您所需要的(假设音频数据的采样频率为44100 Hz):

import sounddevice as sd
sd.play(myarray, 44100)

有关更多详细信息,请参阅文档

它无法读取/写入声音文件,您需要一个单独的库。

Sorry for the late reply, but I think this is a good place to advertise my library …

AFAIK, the standard library has only one module for playing audio: ossaudiodev. Sadly, this only works on Linux and FreeBSD.

UPDATE: There is also winsound, but obviously this is also platform-specific.

For something more platform-independent, you’ll need to use an external library.

My recommendation is the sounddevice module (but beware, I’m the author).

The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:

pip install sounddevice --user

It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).

To play back a NumPy array, that’s all you need (assuming that the audio data has a sampling frequency of 44100 Hz):

import sounddevice as sd
sd.play(myarray, 44100)

For more details, have a look at the documentation.

It cannot read/write sound files, you’ll need a separate library for that.


回答 6

您可以看到以下内容:http : //www.speech.kth.se/snack/

s = Sound() 
s.read('sound.wav') 
s.play()

You can see this: http://www.speech.kth.se/snack/

s = Sound() 
s.read('sound.wav') 
s.play()

回答 7

亚伦的答案似乎比必需的复杂了十倍。如果只需要适用于OS X的答案,请执行以下操作:

from AppKit import NSSound

sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()

一件事…这立即返回。因此,如果您想阻止通话直到声音播放完毕,您可能还想这样做。

from time import sleep

sleep(sound.duration())

编辑:我采用了此功能,并将其与Windows和Linux的变体结合在一起。结果是一个纯Python跨平台模块,没有依赖关系,称为playsound。我已将其上传到pypi。

pip install playsound

然后像这样运行它:

from playsound import playsound
playsound('/path/to/file.wav', block = False)

MP3文件也可以在OS X上使用。WAV应该在所有平台上都可以使用。我不知道平台/文件格式的其他组合是否有效-我还没有尝试过。

Aaron’s answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:

from AppKit import NSSound

sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()

One thing… this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.

from time import sleep

sleep(sound.duration())

Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I’ve uploaded it to pypi.

pip install playsound

Then run it like this:

from playsound import playsound
playsound('/path/to/file.wav', block = False)

MP3 files also work on OS X. WAV should work on all platforms. I don’t know what other combinations of platform/file format do or don’t work – I haven’t tried them yet.


回答 8

这是找到的最简单,最好的方法。它支持Linux / pulseaudio,Mac / coreaudio和Windows / WASAPI。

import soundfile as sf
import soundcard as sc

default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')

default_speaker.play(samples, samplerate=samplerate)

有关大量其他超级有用的功能,请参见https://github.com/bastibe/PySoundFilehttps://github.com/bastibe/SoundCard

This is the easiest & best iv’e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.

import soundfile as sf
import soundcard as sc

default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')

default_speaker.play(samples, samplerate=samplerate)

See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.


回答 9

使用以下代码的类似物,可以在没有任何第三方库的情况下在OS X中播放音频。原始音频数据可以通过wave_wave.writeframes输入。此代码从输入文件中提取4秒的音频。

import wave
import io
from AppKit import NSSound


wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())

wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())

seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()

wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])

wave_shell.close()

wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()

It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.

import wave
import io
from AppKit import NSSound


wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())

wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())

seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()

wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])

wave_shell.close()

wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()

回答 10

尝试PySoundCard使用PortAudio进行回放的(在许多平台上都可以使用)。此外,它还可以识别具有许多通道的“专业”声音设备。

这是自述文件中的一个小示例:

from pysoundcard import Stream

"""Loop back five seconds of audio data."""

fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
    s.write(s.read(blocksize))
s.stop()

Try PySoundCard which uses PortAudio for playback which is available on many platforms. In addition, it recognizes “professional” sound devices with lots of channels.

Here a small example from the Readme:

from pysoundcard import Stream

"""Loop back five seconds of audio data."""

fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
    s.write(s.read(blocksize))
s.stop()

回答 11

同样在OSX-SO,使用OSX的afplay命令:

import subprocess
subprocess.call(["afplay", "path/to/audio/file"])

UPDATE:这一切确实是指定如何做OP想避免在第一时间做的事情。我猜我在这里发布了这个信息,因为OP想要避免的是我所寻找的信息。哎呀

Also on OSX – from SO, using OSX’s afplay command:

import subprocess
subprocess.call(["afplay", "path/to/audio/file"])

UPDATE: All this does is specify how to do what the OP wanted to avoid doing in the first place. I guess I posted this here because what OP wanted to avoid was the info I was looking for. Whoops.


回答 12

Pypi列出了音乐中python的模块。我最喜欢的是jython,因为它有更多的音乐资源和库。作为播放课本中单个音符的代码示例:

# playNote.py 
# Demonstrates how to play a single note.

from music import *   # import music library
note = Note(C4, HN)   # create a middle C half note 
Play.midi(note)       # and play it!

Pypi has a list of modules for python in music. My favorite would be jython because it has more resources and libraries for music. As example of of code to play a single note from the textbook:

# playNote.py 
# Demonstrates how to play a single note.

from music import *   # import music library
note = Note(C4, HN)   # create a middle C half note 
Play.midi(note)       # and play it!

回答 13

Mac OS,我尝试了很多代码,但对我有效

import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
    pygame.mixer.music.play(loops=10, start=0.0)
    time.sleep(10)*to protect from closing*
    pygame.mixer.music.set_volume(10)
    i = i + 1

Mac OS I tried a lot of codes but just this works on me

import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
    pygame.mixer.music.play(loops=10, start=0.0)
    time.sleep(10)*to protect from closing*
    pygame.mixer.music.set_volume(10)
    i = i + 1

回答 14

playsound使用安装软件包:

pip install playsound

用法:

from playsound import playsound
playsound("file location\audio.p3")

Install playsound package using :

pip install playsound

Usage:

from playsound import playsound
playsound("file location\audio.p3")

回答 15

将其放在正在编写的python脚本的顶部:
import subprocess
如果wav文件位于python脚本的目录中:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
如果wav文件不在python脚本的目录中:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
如果您想了解有关游戏的更多信息:
man aplay
Put this at the top of your python script you are writing:
import subprocess
If the wav file IS in the directory of the python script:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
If the wav file IS NOT in the directory of the python script:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
If you want to learn more about aplay:
man aplay

回答 16

要使用python播放通知声音,请调用音乐播放器,例如vlc。VLC提示我改用其命令行版本cvlc。

from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])

需要在设备上预安装vlc。在Linux(Ubuntu 16.04 LTS)上测试;运行Python 3.5。

To play a notification sound using python, call a music player, such as vlc. VLC prompted me to use its commandline version, cvlc, instead.

from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])

It requires vlc to be preinstalled on the device. Tested on Linux(Ubuntu 16.04 LTS); Running Python 3.5.


回答 17

尝试声音设备

如果没有模块pip install sounddevice,请在终端中输入 。

然后在您首选的Python脚本(我使用Juypter)中,输入

import sounddevice as sd

sd.play(audio, sr) 将通过Python播放您想要的内容

获得所需音频和采样率的最佳方法是使用librosa模块。如果没有librosa模块,请在终端中输入此内容。

pip install librosa

audio, sr = librosa.load('wave_file.wav')

无论您要播放什么wav文件,只需确保它与Python脚本位于同一目录即可。这应该允许您通过Python播放所需的wav文件

干杯,查理

聚苯乙烯

一旦音频是“ librosa”数据对象,Python就会将其视为一个numpy数组。作为实验,尝试播放一个长(尝试20,000个数据点)的随机numpy数组。Python应该把它当作白噪声播放。sounddevice模块也播放numpy数组和列表。

Try sounddevice

If you don’t have the module enter pip install sounddevice in your terminal.

Then in your preferred Python script (I use Juypter), enter

import sounddevice as sd

sd.play(audio, sr) will play what you want through Python

The best way to get the audio and samplerate you want is with the librosa module. Enter this in terminal if you don’t have the librosa module.

pip install librosa

audio, sr = librosa.load('wave_file.wav')

Whatever wav file you want to play, just make sure it’s in the same directory as your Python script. This should allow you to play your desired wav file through Python

Cheers, Charlie

P.S.

Once audio is a “librosa” data object, Python sees it as a numpy array. As an experiment, try playing a long (try 20,000 data points) thing of a random numpy array. Python should play it as white noise. The sounddevice module plays numpy arrays and lists as well.


回答 18

在Colab笔记本中,您可以执行以下操作:

from IPython.display import Audio
Audio(waveform, Rate=16000)

In a Colab notebook you can do:

from IPython.display import Audio
Audio(waveform, Rate=16000)

回答 19

我最近使我的音乐播放器在本地支持所有音频文件。我通过找出一种使用vlc python模块以及VLC dll文件的方法来做到这一点。您可以查看一下:https : //github.com/elibroftw/music-caster/blob/master/audio_player.py

I recently made my Music Player support all audio files locally. I did this by figuring out a way to use the vlc python module and also the VLC dll files. You can check it out: https://github.com/elibroftw/music-caster/blob/master/audio_player.py


回答 20

如果您使用的是OSX,则可以使用“ os”模块或“子进程”等调用OSX的“播放”命令。从OSX Shell来看,

播放“ bah.wav”

它会在我的计算机上播放约半秒钟。

If you’re on OSX, you can use the “os” module or “subprocess” etc. to call the OSX “play” command. From the OSX shell, it looks like

play “bah.wav”

It starts to play in about a half-second on my machine.


回答 21

简单地说,您可以在cvlc的帮助下完成此操作-我是这样完成的:

import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")

/home/maulo/selfProject/task.mp3。这是我的mp3文件的位置。借助“ –play-and-exit”,您将能够再次播放声音而无需结束vlc进程。

Simply You can do it with the help of cvlc- I did it in this way:

import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")

/home/maulo/selfProject/task.mp3. This is the location of my mp3 file. with the help of “–play-and-exit” you will be able to play again the sound without ending the vlc process.