mirror of
https://github.com/RGBCube/serenity
synced 2025-07-25 04:17:35 +00:00
Piano: Use a secondary thread to write the audio stream.
This frees up the main thread to draw the GUI. The secondary thread uses a pipe to trick the main thread's event loop to break out of select() and update() the PianoWidget. :^)
This commit is contained in:
parent
dcfa93e71f
commit
eec9666735
3 changed files with 88 additions and 54 deletions
|
@ -1,20 +1,19 @@
|
|||
#include "Music.h"
|
||||
#include "PianoWidget.h"
|
||||
#include <LibCore/CFile.h>
|
||||
#include <LibCore/CNotifier.h>
|
||||
#include <LibGUI/GApplication.h>
|
||||
#include <LibGUI/GEventLoop.h>
|
||||
#include <LibGUI/GWindow.h>
|
||||
|
||||
static int s_pipefds[2];
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
CFile audio("/dev/audio");
|
||||
if (!audio.open(CIODevice::WriteOnly)) {
|
||||
dbgprintf("Can't open audio device: %s", audio.error_string());
|
||||
return 1;
|
||||
}
|
||||
|
||||
GApplication app(argc, argv);
|
||||
|
||||
pipe(s_pipefds);
|
||||
|
||||
auto* window = new GWindow;
|
||||
window->set_title("Piano");
|
||||
window->set_rect(100, 100, 512, 512);
|
||||
|
@ -24,12 +23,30 @@ int main(int argc, char** argv)
|
|||
|
||||
window->show();
|
||||
|
||||
for (;;) {
|
||||
GEventLoop::current().pump(GEventLoop::WaitMode::PollForEvents);
|
||||
u8 buffer[4096];
|
||||
piano_widget->fill_audio_buffer(buffer, sizeof(buffer));
|
||||
audio.write(buffer, sizeof(buffer));
|
||||
}
|
||||
CNotifier notifier(s_pipefds[0], CNotifier::Read);
|
||||
notifier.on_ready_to_read = [&] {
|
||||
char buffer[32];
|
||||
read(s_pipefds[1], buffer, sizeof(buffer));
|
||||
piano_widget->update();
|
||||
};
|
||||
|
||||
return 0;
|
||||
create_thread([](void* context) -> int {
|
||||
auto* piano_widget = (PianoWidget*)context;
|
||||
|
||||
CFile audio("/dev/audio");
|
||||
if (!audio.open(CIODevice::WriteOnly)) {
|
||||
dbgprintf("Can't open audio device: %s", audio.error_string());
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
u8 buffer[4096];
|
||||
piano_widget->fill_audio_buffer(buffer, sizeof(buffer));
|
||||
audio.write(buffer, sizeof(buffer));
|
||||
char ch = '!';
|
||||
write(s_pipefds[0], &ch, 1);
|
||||
}
|
||||
}, piano_widget);
|
||||
|
||||
return app.exec();
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue