1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
#include <libreichwein/file.h>
#include <alsa/asoundlib.h>
#include <cstdint>
#include <cmath>
#include <iostream>
#include <limits>
static const char *device = "default"; /* playback device */
const snd_pcm_sframes_t nframes = 1024; // ~1/44th sec buffer size
int16_t buffer[nframes]; /* some random data */
const unsigned int f_sample = 44100;
const double pi = std::acos(-1);
class ClickStream
{
private:
std::vector<uint16_t> m_data;
public:
ClickStream()
{
std::string data_s = Reichwein::File::getFile("media/click.s16le");
m_data.resize(data_s.size() / 2);
memcpy(m_data.data(), data_s.data(), data_s.size());
}
double generate(double phase)
{
int i;
size_t j = phase;
for (i = 0; i < nframes; i++) {
if (j >= m_data.size())
j = 0;
buffer[i] = m_data[j];
j++;
}
return j;
}
};
class PCM
{
public:
PCM()
{
// non-blocking
if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
if ((err = snd_pcm_set_params(handle,
SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
f_sample,
1,
20000)) < 0) { /* 0.5sec */
printf("Playback open error: %s\n", snd_strerror(err));
exit(EXIT_FAILURE);
}
}
~PCM()
{
/* pass the remaining samples, otherwise they're dropped in close */
err = snd_pcm_drain(handle);
if (err < 0)
printf("snd_pcm_drain failed: %s\n", snd_strerror(err));
snd_pcm_close(handle);
}
// write from buffer to ALSA PCM
bool write()
{
frames = snd_pcm_writei(handle, buffer, nframes);
if (frames < 0) {
std::cout << "Recovering." << std::endl;
frames = snd_pcm_recover(handle, frames, 0);
}
if (frames < 0) {
printf("snd_pcm_writei failed: %s\n", snd_strerror(frames));
return false;
}
if (frames > 0 && frames < nframes)
printf("Short write (expected %li, wrote %li)\n", nframes, frames);
return frames == 0;
}
private:
int err;
snd_pcm_t *handle;
snd_pcm_sframes_t frames;
};
int main(void)
{
PCM pcm;
double phase = 0;
ClickStream stream;
for (unsigned int i = 0; i < 50; i++) {
phase = stream.generate(phase);
pcm.write();
}
return 0;
}
|