Working with sounds in Python

Working with sounds in Python

I didn't understand how to handle sounds in Python, so I summarized it roughly.

Basically, I referred to this site Playing and Recording Sound in Python.

Regeneration

An example of a library that plays audio

playsound

Only the playsound function is implemented, and a WAV file or MP3 file is specified and played.

install

pip install playsound

usage

from playsound import playsound

playsound("sample.wav")

simpleaudio

Play a WAV file or NumPy array. It is also possible to determine whether it is playing.

install

pip install simpleaudio

usage

import simpleaudio

wav_obj = simpleaudio.WaveObject.from_wave_file("sample.wav")
play_obj = wav_obj.play()
play_obj.wait_done()
#Check if it is playing
if play_obj.is_playing():
	print("still playing")

winsound

For Windows, is winsound available by default? WAV files and beeps can be played.

usage

import winsound

winsound.PlaySound("sample.wav", winsound.SND_FILENAME)
#Beep playback
import winsound

winsound.Beep(1000, 100) #Play 1000Hz beep for 100ms

python-sounddevice

Provides binding for the PortAudio library. Provides functionality for playing / recording audio signals and NumPy arrays.

install

If you are using Anaconda, you can install it with the conda package

conda install -c conda-forge python-sounddevice

usage

import sounddevice as sd
import wave
import numpy as np

wf = wave.open("sample.wav")
fs = wf.getframerate()
data = wf.readframes(wf.getnframes())
data = np.frombuffer(data, dtype='int16')

sd.play(data, fs)
status = sd.wait()

The above handles the entire song at once, but when performing real-time processing, it is necessary to handle the audio signal in short units by callback processing.

import sounddevice as sd

duration = 5.5

def callback(indata, outdata, frames, time, status):
    if status:
        print(status)
    outdata[:] = indata

with sd.Stream(channels=2, callback=callback):
    sd.sleep(int(duration * 1000))

pydub

install

pip install pydub

When using non-WAV files such as MP3, you also need to install ffmpeg or libav.

In addition, you need to install one of the following to play audio (simpleaudio is recommended)

usage

from pydub import AudioSegment
from pydub.playback import play

sound = AudioSegment.from_file("sample.wav", format="wav")
play(sound)

pyaudio

Provides binding for the PortAudio library. Easy audio playback and recording on cross-platform.

Playing simple audio is more complicated than other methods, so if you just want to play a file, you should choose another method.

However, it is possible to set input / output devices and check latency for control at a lower level. Also, since it can be described in callback, it is suitable for performing relatively complicated processing.

install

pip install pyaudio

#Also possible with conda
conda install pyaudio

usage

import pyaudio
import wave
import sys

chunk = 1024

wf = wave.open("sample.wav", "rb")
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True)
data = wf.readframes(chunk)

while data != '':
    stream.write(data)
    data = wf.readframes(chunk)

stream.stop_stream()
stream.close()
p.terminate()

recording

An example of a library that can record audio

python-sounddevice

usage

import sounddevice as sd
from scipy.io.wavfile import write

record_second = 3
fs = 44100

myrecording = sd.rec(int(record_second * fs), samplerate=fs, channels=2)

write('output.wav', fs, myrecording)

pyaudio

usage

import pyaudio
import wave

chunk = 1024
format = pyaudio.paInt16
channels = 2
fs = 44100
record_second = 3

p = pyaudio.PyAudio()
stream = p.open(format=format, channels=channels, rate=fs, input=True, frames_per_buffer=chunk)

print("* recording")

frames = []

for i in range(int(fs / chunk * record_second)):
    data = stream.read(chunk)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open("output.wav", "wb")
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()

device

Since you may want to specify the playback / recording device, check how to change it in each library.

python-sounddevice

Show available devices and selected devices

import sounddevice as sd
sd.query_devices()

Execution example b985e173.png

You can also use the following command on the terminal.

python -m sounddevice

The device can be selected by setting the device ID to default.device or assigning it toplay ()andStream ()as a device argument.

import sounddevice as sd
sd.default.device = 1, 5

Recommended Posts

Working with sounds in Python
Working with LibreOffice in Python
Working with LibreOffice in Python: import
Working with DICOM images in Python
Try working with binary data in Python
Post Test 3 (Working with PosgreSQL in Python)
Try working with Mongo in Python on Mac
[Introduction for beginners] Working with MySQL in Python
Scraping with selenium in Python
Scraping with chromedriver in python
Debugging with pdb in Python
Python: Working with Firefox with selenium
Scraping with Selenium in Python
Scraping with Tor in Python
Tweet with image in Python
Combined with permutations in Python
Explain in detail how to make sounds with python
Number recognition in images with Python
GOTO in Python with Sublime Text 3
Scraping with Selenium in Python (Basic)
CSS parsing with cssutils in Python
Numer0n with items made in Python
Open UTF-8 with BOM in Python
Use rospy with virtualenv in Python3
Use Python in pyenv with NeoVim
Heatmap with Dendrogram in Python + matplotlib
Read files in parallel with Python
Password generation in texto with python
Use OpenCV with Python 3 in Window
Until dealing with python in Atom
Get started with Python in Blender
Write documentation in Sphinx with Python Livereload
Get additional data in LDAP with python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Try logging in to qiita with Python
Stress Test with Locust written in Python
Exclusive control with lock file in Python
Statistics with python
Device monitoring with On-box Python in IOS-XE
Meta-analysis in Python
Unittest in python
Python with Go
Draw Nozomi Sasaki in Excel with python
Tips for dealing with binaries in Python
Display Python 3 in the browser with MAMP
Page cache in Python + Flask with Flask-Caching
Twilio with Python
Epoch in Python
Discord in Python
Integrate with Python
How to work with BigQuery in Python
Playing card class in Python (with comparison)
Sudoku in Python
DCI in Python