* How to know how much audio has been played?
[not found] <18457ff3ab28c900-webhooks-bot@alsa-project.org>
@ 2025-06-03 9:58 ` GitHub issues - opened
0 siblings, 0 replies; only message in thread
From: GitHub issues - opened @ 2025-06-03 9:58 UTC (permalink / raw)
To: alsa-devel
alsa-project/alsa-lib issue #458 was opened from yangyagami:
I tried to get an answer from AI, but the result has discrepancies.
```cpp
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <thread>
#include <alsa/asoundlib.h>
#define SAMPLE_RATE 44100
#define FREQUENCY 440.0 // A4 note
#define DURATION 5.0 // seconds
using namespace std::chrono_literals;
int main() {
snd_pcm_t *handle;
snd_pcm_hw_params_t *params;
unsigned int rate = SAMPLE_RATE;
int dir;
int pcm;
pcm = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
if (pcm < 0) {
std::cerr << "Unable to open PCM device: " << snd_strerror(pcm) << std::endl;
return 1;
}
snd_pcm_hw_params_alloca(¶ms);
snd_pcm_hw_params_any(handle, params);
snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);
snd_pcm_hw_params_set_rate_near(handle, params, &rate, &dir);
snd_pcm_hw_params_set_channels(handle, params, 1);
pcm = snd_pcm_hw_params(handle, params);
if (pcm < 0) {
std::cerr << "Unable to set HW parameters: " << snd_strerror(pcm) << std::endl;
return 1;
}
int samples = static_cast<int>(DURATION * SAMPLE_RATE);
int16_t *buffer = new int16_t[samples];
for (int i = 0; i < samples; ++i) {
buffer[i] = static_cast<int16_t>(32767 * sin(2 * M_PI * FREQUENCY * i / SAMPLE_RATE));
}
pcm = snd_pcm_writei(handle, buffer, samples);
if (pcm < 0) {
std::cerr << "Playback error: " << snd_strerror(pcm) << std::endl;
}
while (true) {
snd_pcm_sframes_t delay;
int rc = snd_pcm_delay(handle, &delay);
if (rc == 0) {
double played_sec = (samples - delay) / 44100.0f;
printf("Played: %.2f sec\n", played_sec);
} else {
std::cerr << snd_strerror(rc) << std::endl;
break;
}
}
snd_pcm_drain(handle);
delete[] buffer;
snd_pcm_close(handle);
return 0;
}
```
Issue URL : https://github.com/alsa-project/alsa-lib/issues/458
Repository URL: https://github.com/alsa-project/alsa-lib
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2025-06-03 9:59 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
[not found] <18457ff3ab28c900-webhooks-bot@alsa-project.org>
2025-06-03 9:58 ` How to know how much audio has been played? GitHub issues - opened
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.