MCPcopy Create free account
hub / github.com/cactus-compute/cactus / record_audio

Function record_audio

tests/chat.cpp:62–123  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

60}
61
62bool record_audio(std::vector<uint8_t>& pcm_out) {
63 if (SDL_Init(SDL_INIT_AUDIO) < 0) {
64 std::cerr << "Failed to init SDL: " << SDL_GetError() << "\n";
65 return false;
66 }
67
68 int num_devices = SDL_GetNumAudioDevices(1);
69 if (num_devices == 0) {
70 std::cerr << "No audio capture devices found\n";
71 SDL_QuitSubSystem(SDL_INIT_AUDIO);
72 return false;
73 }
74
75 SDL_AudioSpec want, have;
76 SDL_zero(want);
77 want.freq = RECORD_SAMPLE_RATE;
78 want.format = AUDIO_S16LSB;
79 want.channels = 1;
80 want.samples = (RECORD_SAMPLE_RATE * 100) / 1000;
81 want.callback = record_callback;
82
83 SDL_AudioDeviceID device = SDL_OpenAudioDevice(nullptr, 1, &want, &have, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
84 if (device == 0) {
85 std::cerr << "Failed to open mic: " << SDL_GetError() << "\n";
86 SDL_QuitSubSystem(SDL_INIT_AUDIO);
87 return false;
88 }
89
90 g_record.actual_sample_rate = have.freq;
91 g_record.buffer.clear();
92 g_record.recording = true;
93 SDL_PauseAudioDevice(device, 0);
94
95 std::cout << "Recording... press Enter to stop.\n" << std::flush;
96
97 std::atomic<bool> stop{false};
98 std::thread input_thread([&stop]() {
99 std::string line;
100 std::getline(std::cin, line);
101 stop = true;
102 });
103
104 while (!stop) {
105 std::this_thread::sleep_for(std::chrono::milliseconds(50));
106 }
107
108 g_record.recording = false;
109 SDL_PauseAudioDevice(device, 1);
110
111 {
112 std::lock_guard<std::mutex> lock(g_record.mutex);
113 pcm_out = resample_s16(g_record.buffer, g_record.actual_sample_rate, RECORD_SAMPLE_RATE);
114 }
115
116 double duration = (pcm_out.size() / 2) / static_cast<double>(RECORD_SAMPLE_RATE);
117 std::cout << "Recorded " << std::fixed << std::setprecision(1) << duration << "s of audio.\n";
118
119 input_thread.join();

Callers 1

mainFunction · 0.85

Calls 3

resample_s16Function · 0.85
sizeMethod · 0.80
clearMethod · 0.45

Tested by

no test coverage detected