summaryrefslogtreecommitdiff
path: root/src/audio.rs
blob: 961c8eda58834a277972043f67f9f2cfad48bc4c (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
use alto::{Alto, Stereo, StreamingSource};
use lewton::inside_ogg::OggStreamReader;
use std::fs::File;

use crate::constants;

pub fn init() -> (StreamingSource, Vec<i16>) {
    let mut source = OggStreamReader::new(File::open("data/djbLUETOOTH.ogg").unwrap()).unwrap();
    let alto = Alto::load_default().unwrap();
    let device = alto.open(None).unwrap();
    let audio_context = device.new_context(None).unwrap();
    let mut stream = audio_context.new_streaming_source().unwrap();
    let sample_rate = source.ident_hdr.audio_sample_rate as i32;
    let sample_channels =
        source.ident_hdr.audio_channels as f32 * source.ident_hdr.audio_sample_rate as f32;

    let mut waveform = Vec::new();

    let mut _track_length = 0.0;

    while let Ok(Some(mut samples)) = source.read_dec_packet_itl() {
        samples = samples
            .into_iter()
            .map(|s| (s as f32 * constants::VOLUME) as i16)
            .collect();

        let audio_buffer = audio_context
            .new_buffer::<Stereo<i16>, _>(&samples, sample_rate)
            .unwrap();
        stream.queue_buffer(audio_buffer).unwrap();

        _track_length += samples.len() as f32 / sample_channels;

        waveform.append(
            &mut samples
                .into_iter()
                .enumerate()
                .filter(|(i, _)| i % 2 == 0)
                .map(|(_, s)| s)
                .collect(),
        );
    }

    (stream, waveform)
}