1#!/usr/bin/env python
2""" pygame.examples.audiocapture
3
4A pygame 2 experiment.
5
6* record sound from a microphone
7* play back the recorded sound
8"""
9import pygame as pg
10import time
11
12if pg.get_sdl_version()[0] < 2:
13    raise SystemExit("This example requires pygame 2 and SDL2.")
14
15from pygame._sdl2 import (
16    get_audio_device_name,
17    get_num_audio_devices,
18    AudioDevice,
19    AUDIO_F32,
20    AUDIO_ALLOW_FORMAT_CHANGE,
21)
22from pygame._sdl2.mixer import set_post_mix
23
24
25pg.mixer.pre_init(44100, 32, 2, 512)
26pg.init()
27
28# init_subsystem(INIT_AUDIO)
29names = [get_audio_device_name(x, 1) for x in range(get_num_audio_devices(1))]
30print(names)
31
32iscapture = 1
33sounds = []
34sound_chunks = []
35
36
37def callback(audiodevice, audiomemoryview):
38    """This is called in the sound thread.
39
40    Note, that the frequency and such you request may not be what you get.
41    """
42    # print(type(audiomemoryview), len(audiomemoryview))
43    # print(audiodevice)
44    sound_chunks.append(bytes(audiomemoryview))
45
46
47def postmix_callback(postmix, audiomemoryview):
48    """This is called in the sound thread.
49
50    At the end of mixing we get this data.
51    """
52    print(type(audiomemoryview), len(audiomemoryview))
53    print(postmix)
54
55
56set_post_mix(postmix_callback)
57
58audio = AudioDevice(
59    devicename=names[0],
60    iscapture=1,
61    frequency=44100,
62    audioformat=AUDIO_F32,
63    numchannels=2,
64    chunksize=512,
65    allowed_changes=AUDIO_ALLOW_FORMAT_CHANGE,
66    callback=callback,
67)
68# start recording.
69audio.pause(0)
70
71print("recording with :%s:" % names[0])
72time.sleep(5)
73
74
75print("Turning data into a pg.mixer.Sound")
76sound = pg.mixer.Sound(buffer=b"".join(sound_chunks))
77
78print("playing back recorded sound")
79sound.play()
80time.sleep(5)
81pg.quit()
82