Presentation by Jean Cruypenynck/@nonatomiclabs
import pyaudio
pip install pyaudio
pyaudio.PyAudio
pyaudio.Stream
import pyaudio
1. Import the package
2. Create an instance of PyAudio
p = pyaudio.PyAudio()
3. Open an audio stream
stream = p.open(…)
4. Start the stream
stream.start_stream()
5. Close the stream when you're done
stream.close()
open(rate,
format,
channels,
input=False,
output=False,
input_device_index=None,
output_device_index=None,
frames_per_buffer=1024,
start=True,
input_host_api_specific_stream_info=None,
output_host_api_specific_stream_info=None,
stream_callback=None)
open()
stream_callback
def callback(in_data, frame_count,
time_info, status_flags):
# PROCESSING
out_data = in_data
return (out_data, pyaudio.PaContinue)
Function called every time audio is needed
(full input buffer/empty output buffer)
import sys
import pyaudio
import math
import struct
import time
# Instantiate PyAudio
p = pyaudio.PyAudio()
# Open stream using callback
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=48000,
frames_per_buffer=1024,
input=True,
output=True,
stream_callback=callback)
# Close the stream after 10 seconds
time.sleep(10)
stream.close()
def callback(in_data, frame_count, time_info, status):
levels = []
for _i in range(1024):
levels.append(struct.unpack('<h', in_data[_i:_i + 2])[0])
avg_chunk = sum(levels)/len(levels)
print_audio_level(avg_chunk, time_info['current_time'])
return (in_data, pyaudio.paContinue)
import pyaudio
import wave
import sys
BUFFER_SIZE = 1024
# Opening audio file as binary data
wf = wave.open(sys.argv[1], 'rb')
# Instantiate PyAudio
p = pyaudio.PyAudio()
file_sw = wf.getsampwidth()
stream = p.open(format=p.get_format_from_width(file_sw),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(BUFFER_SIZE)
while data != '':
stream.write(data)
data = wf.readframes(BUFFER_SIZE)
stream.stop_stream()
stream.close()
p.terminate()
all real-time!