では8分音符と16分音符と32分音符と三連符はどう書けばいいの?
音符の長さについては、サンプリングレートとBPMを使って計算することができます。以下は、基本的な8分音符、16分音符、32分音符、および3連符を生成するためのサンプルコードです。
extern crate hound;
use std::f32::consts::PI;
use std::i16;
fn main() {
// 生成する音のパラメータを設定
let sample_rate = 44100;
let bpm = 120;
let quarter_note_duration = 60.0 / bpm as f32;
let eighth_note_duration = quarter_note_duration / 2.0;
let sixteenth_note_duration = quarter_note_duration / 4.0;
let thirtysecond_note_duration = quarter_note_duration / 8.0;
let triplet_duration = eighth_note_duration / 3.0;
let a_frequency = 440.0;
// 8分音符を生成する
let mut samples: Vec<i16> = Vec::new();
for i in 0..(sample_rate as f32 * eighth_note_duration) as usize {
let t = i as f32 / sample_rate as f32;
let sample = (t * a_frequency * 2.0 * PI).sin();
samples.push((sample * i16::MAX as f32) as i16);
}
// 16分音符を生成する
let mut sixteenth_note_samples: Vec<i16> = Vec::new();
for i in 0..(sample_rate as f32 * sixteenth_note_duration) as usize {
let t = i as f32 / sample_rate as f32;
let sample = (t * a_frequency * 2.0 * PI).sin();
sixteenth_note_samples.push((sample * i16::MAX as f32) as i16);
}
samples.extend(&sixteenth_note_samples);
samples.extend(&sixteenth_note_samples);
// 32分音符を生成する
let mut thirtysecond_note_samples: Vec<i16> = Vec::new();
for i in 0..(sample_rate as f32 * thirtysecond_note_duration) as usize {
let t = i as f32 / sample_rate as f32;
let sample = (t * a_frequency * 2.0 * PI).sin();
thirtysecond_note_samples.push((sample * i16::MAX as f32) as i16);
}
samples.extend(&thirtysecond_note_samples);
samples.extend(&thirtysecond_note_samples);
samples.extend(&thirtysecond_note_samples);
samples.extend(&thirtysecond_note_samples);
// 3連符を生成する
let mut triplet_samples: Vec<i16> = Vec::new();
for i in 0..(sample_rate as f32 * triplet_duration) as usize {
let t = i as f32 / sample_rate as f32;
let sample = (t * a_frequency * 2.0 * PI).sin();
triplet_samples.push((sample * i16::MAX as f32) as i16);
}
samples.extend(&triplet_samples);
samples.extend(&triplet_samples);
samples.extend(&triplet_samples);
// 音声ファイルに書き出す
let spec = hound::WavSpec {
channels: 1,
sample_rate: sample_rate,
bits_per_sample: