Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created July 14, 2023 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kujirahand/fac0309bc0c16ac0a3bb79201ed51a79 to your computer and use it in GitHub Desktop.
Save kujirahand/fac0309bc0c16ac0a3bb79201ed51a79 to your computer and use it in GitHub Desktop.
Play tone SoundFont
/*
file: Cargo.tml
[dependencies]
rustysynth = "1.2.0"
tinyaudio = "0.1.1"
*/
use rustysynth::{SoundFont, Synthesizer, SynthesizerSettings};
use std::fs::File;
use std::sync::Arc;
use tinyaudio::prelude::*;
fn main() {
// Load the SoundFont.
let mut sf2 = File::open("TimGM6mb.sf2").unwrap();
let sound_font = Arc::new(SoundFont::new(&mut sf2).unwrap());
// Create the synthesizer.
let settings = SynthesizerSettings::new(44100);
let mut synthesizer = Synthesizer::new(&sound_font, &settings).unwrap();
// Play some notes (middle C, E, G).
synthesizer.process_midi_message(0, 0xC0, 80, 0); // VoiceChange
synthesizer.note_on(0, 60, 100);
synthesizer.note_on(0, 64, 100);
synthesizer.note_on(0, 67, 100);
// The output buffer (3 seconds).
let sample_count = (3 * settings.sample_rate) as usize;
let mut left: Vec<f32> = vec![0_f32; sample_count];
let mut right: Vec<f32> = vec![0_f32; sample_count];
// Render the waveform.
synthesizer.render(&mut left[..], &mut right[..]);
//////
// Setup the audio output.
let params = OutputDeviceParameters {
channels_count: 2,
sample_rate: 44100,
channel_sample_count: 4410,
};
let _device = run_output_device(params, {
let mut clock = 0f32;
move |data| {
for samples in data.chunks_mut(params.channels_count) {
clock = (clock + 1.0) % params.sample_rate as f32;
let value = left[clock as usize % left.len()];
for sample in samples {
*sample = value;
}
}
}
})
.unwrap();
// Wait for 10 seconds.
std::thread::sleep(std::time::Duration::from_secs(10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment