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.
An example of a library that plays audio
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")
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")
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
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))
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)
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()
An example of a library that can record audio
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)
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()
Since you may want to specify the playback / recording device, check how to change it in each library.
Show available devices and selected devices
import sounddevice as sd
sd.query_devices()
Execution example
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