summaryrefslogtreecommitdiffstats
path: root/third_party/rust/cubeb/examples/tone.rs
blob: 97e940bc9490f37aa4175546cc104d4bc6abdfef (plain)
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
// Copyright © 2011 Mozilla Foundation
//
// This program is made available under an ISC-style license.  See the
// accompanying file LICENSE for details.

//! libcubeb api/function test. Plays a simple tone.
extern crate cubeb;

mod common;

use cubeb::{MonoFrame, Sample};
use std::f32::consts::PI;
use std::thread;
use std::time::Duration;

const SAMPLE_FREQUENCY: u32 = 48_000;
const STREAM_FORMAT: cubeb::SampleFormat = cubeb::SampleFormat::S16LE;

type Frame = MonoFrame<i16>;

fn main() {
    let ctx = common::init("Cubeb tone example").expect("Failed to create cubeb context");

    let params = cubeb::StreamParamsBuilder::new()
        .format(STREAM_FORMAT)
        .rate(SAMPLE_FREQUENCY)
        .channels(1)
        .layout(cubeb::ChannelLayout::MONO)
        .take();

    let mut position = 0u32;

    let mut builder = cubeb::StreamBuilder::<Frame>::new();
    builder
        .name("Cubeb tone (mono)")
        .default_output(&params)
        .latency(0x1000)
        .data_callback(move |_, output| {
            // generate our test tone on the fly
            for f in output.iter_mut() {
                // North American dial tone
                let t1 = (2.0 * PI * 350.0 * position as f32 / SAMPLE_FREQUENCY as f32).sin();
                let t2 = (2.0 * PI * 440.0 * position as f32 / SAMPLE_FREQUENCY as f32).sin();

                f.m = i16::from_float(0.5 * (t1 + t2));

                position += 1;
            }
            output.len() as isize
        })
        .state_callback(|state| {
            println!("stream {:?}", state);
        });

    let stream = builder.init(&ctx).expect("Failed to create cubeb stream");

    stream.start().unwrap();
    thread::sleep(Duration::from_millis(500));
    stream.stop().unwrap();
}