play back sine tone

This commit is contained in:
Sébastien Bourdeauducq 2024-12-26 16:18:43 +08:00
parent e16f1a90a7
commit cd66e84cee
2 changed files with 77 additions and 0 deletions

View File

@ -2,6 +2,7 @@ PROG= sndlock
SRCS= imgui_impl_glfw.cpp imgui_impl_opengl3.cpp imgui_draw.cpp imgui_widgets.cpp imgui_tables.cpp imgui.cpp sndlock.cpp
CXXOPTS= `pkg-config --cflags glfw3 gl`
LDFLAGS= `pkg-config --libs glfw3 gl`
LDADD= -lsndio -lm
BINDIR= /usr/local/bin
NOMAN= noman

View File

@ -1,11 +1,72 @@
#include <iostream>
#include <thread>
#include <cstdint>
#include <GLFW/glfw3.h>
#include <sndio.h>
#include <math.h>
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
static std::atomic<bool> shutdown_threads;
static std::atomic<float> frequency = 440.0f;
#define SND_SIG 1
#define SND_BITS 16
#define SND_PCHAN 2
#define SND_RATE 44100
#define SND_BUFLEN 4096
static void dsp_thread()
{
struct sio_hdl *hdl;
struct sio_par par;
hdl = sio_open(SIO_DEVANY, SIO_PLAY, 0);
if(hdl == nullptr) {
std::cerr << "failed to open sound device" << std::endl;
return;
}
sio_initpar(&par);
par.sig = SND_SIG;
par.bits = SND_BITS;
par.pchan = SND_PCHAN;
par.rate = SND_RATE;
par.le = SIO_LE_NATIVE;
if(!sio_setpar(hdl, &par)) {
std::cerr << "failed to set sound device parameters" << std::endl;
sio_close(hdl);
return;
}
if(!sio_start(hdl)) {
std::cerr << "failed to start sound device" << std::endl;
sio_close(hdl);
return;
}
uint32_t phase = 0;
int16_t buf[SND_BUFLEN*SND_PCHAN];
while(!shutdown_threads) {
uint32_t ftw = frequency*(float)UINT32_MAX/SND_RATE;
for(int i=0;i<SND_BUFLEN;i++) {
buf[2*i] = buf[2*i+1] = (INT16_MAX-1)*sin(phase*2.0f*(float)M_PI/(float)UINT32_MAX);
phase += ftw;
}
if(!sio_write(hdl, buf, SND_BUFLEN*(SND_BITS/8)*SND_PCHAN)) {
std::cerr << "failed to write to sound device" << std::endl;
sio_stop(hdl);
sio_close(hdl);
return;
}
}
sio_stop(hdl);
sio_close(hdl);
}
int main(int argc, char* argv[])
{
if(!glfwInit()) {
@ -41,6 +102,18 @@ int main(int argc, char* argv[])
ImGui_ImplOpenGL3_Init("#version 130");
std::atexit(ImGui_ImplOpenGL3_Shutdown);
static std::thread dsp_thread_h = std::thread(dsp_thread);
static auto JoinDSP = []() {
dsp_thread_h.join();
};
std::atexit(JoinDSP);
shutdown_threads = false;
static auto SetShutdown = []() {
shutdown_threads = true;
};
std::atexit(SetShutdown);
bool exit = false;
while(!exit && !glfwWindowShouldClose(window)) {
glfwPollEvents();
@ -56,6 +129,9 @@ int main(int argc, char* argv[])
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::Begin("sndlock", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoResize);
float frequency_l = frequency;
ImGui::SliderFloat("Frequency", &frequency_l, 50.0f, 8000.0f);
frequency = frequency_l;
if(ImGui::Button("Exit"))
exit = true;