Projekt

Allgemein

Profil

Feature #751 » main.cpp

Maximilian Seesslen, 02.04.2026 13:34

 
1
#include <pulse/simple.h>
2
#include <pulse/error.h>
3
#include <cmath>
4
#include <thread>
5
#include <atomic>
6
#include <iostream>
7

    
8
std::atomic<bool> running{true};
9
float gfreq=440;
10

    
11
void playTone(float freq, float durationSec) {
12
    const int sample_rate = 44100;
13

    
14
    pa_sample_spec ss;
15
    ss.format = PA_SAMPLE_FLOAT32LE;
16
    ss.rate = sample_rate;
17
    ss.channels = 1;
18

    
19
    int error;
20
    pa_simple *s = pa_simple_new(
21
        nullptr,
22
        "ToneGenerator",
23
        PA_STREAM_PLAYBACK,
24
        nullptr,
25
        "Playback",
26
        &ss,
27
        nullptr, nullptr,
28
        &error
29
    );
30

    
31
    if (!s) {
32
        std::cerr << "PulseAudio error: " << pa_strerror(error) << "\n";
33
        return;
34
    }
35

    
36
    int total_samples = durationSec * sample_rate;
37

    
38
    for (int i = 0; i < total_samples && running; i++) {
39
        float sample = sinf(2.0f * M_PI * gfreq * i / sample_rate);
40

    
41
        if (pa_simple_write(s, &sample, sizeof(sample), &error) < 0) {
42
            std::cerr << "pa_simple_write() failed: " << pa_strerror(error) << "\n";
43
            break;
44
        }
45
    }
46

    
47
    pa_simple_drain(s, &error);
48
    pa_simple_free(s);
49
}
50

    
51
int main() {
52
    std::cout << "Starting tone in background...\n";
53

    
54
    std::thread t([](){
55
        playTone(440.0f, 5.0f);   // 5 seconds in background
56
    });
57

    
58
    // Main program continues running
59
    std::cout << "Main program is free to do other work...\n";
60

    
61
    // Simulate work
62
    //std::this_thread::sleep_for(std::chrono::seconds(2));
63
    //std::cout << "Still running...\n";
64

    
65
    for(int i1=0; i1<10; i1++)
66
    {
67
      usleep(1000000/2);
68
      gfreq+=100;
69
    }
70

    
71
    t.join();
72
    std::cout << "Tone finished.\n";
73
}
(1-1/2)