Created
July 14, 2023 07:00
-
-
Save kujirahand/c055c9585baef8f60352dbd823689760 to your computer and use it in GitHub Desktop.
SoundFontを使ってWAVファイル作成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::sync::Arc; | |
use rustysynth::{SynthesizerSettings, Synthesizer, SoundFont}; | |
use wav_io; | |
fn main() { | |
// サンプリング周波数(CD音質)を指定 --- (*1) | |
const SAMPLE_RATE: u32 = 44_100; | |
const SAMPLE_LEN: usize = (SAMPLE_RATE * 2) as usize; // 2秒分のデータ | |
// データの書き込み先を準備 --- (*2) | |
let mut samples:Vec<f32> = vec![]; | |
let mut left_buf = [0.0f32; SAMPLE_LEN]; | |
let mut right_buf = [0.0f32; SAMPLE_LEN]; | |
// 用意したサウンドフォントを読み込む --- (*3) | |
let mut sf2 = File::open("TimGM6mb.sf2").unwrap(); | |
let sound_font = Arc::new(SoundFont::new(&mut sf2).unwrap()); | |
// シンセサイザーの作成 --- (*4) | |
let settings = SynthesizerSettings::new(SAMPLE_RATE as i32); | |
let mut synthesizer = Synthesizer::new(&sound_font, &settings).unwrap(); | |
// 音量と音色を変更 --- (*5) | |
synthesizer.set_master_volume(1.0); // 音量を設定 | |
synthesizer.process_midi_message(0, 0xC0, 0, 0); // ピアノ(no:0)に設定 | |
// ドミソの和音を鳴らす --- (*6) | |
synthesizer.note_on(0, 60, 120); // ド (ch, note, velocity) | |
synthesizer.note_on(0, 64, 120); // ミ | |
synthesizer.note_on(0, 67, 120); // ソ | |
// バッファに波形を書き込む --- (*7) | |
synthesizer.render(&mut left_buf, &mut right_buf); | |
// WAVファイル保存用に左右チャンネルのデータを書き込み --- (*8) | |
for i in 0..SAMPLE_LEN { | |
samples.push(left_buf[i]); | |
samples.push(right_buf[i]); | |
} | |
// ドミソの音を消す --- (*9) | |
synthesizer.note_off_all(true); | |
// レファラの音を鳴らす --- (*10) | |
synthesizer.note_on(0, 62, 120); | |
synthesizer.note_on(0, 65, 120); | |
synthesizer.note_on(0, 69, 120); | |
synthesizer.render(&mut left_buf, &mut right_buf); | |
for i in 0..SAMPLE_LEN { | |
samples.push(left_buf[i]); | |
samples.push(right_buf[i]); | |
} | |
synthesizer.note_off_all(true); | |
// WAVファイルを保存 --- (*11) | |
let mut wav_head = wav_io::new_stereo_header(); | |
wav_head.sample_rate = SAMPLE_RATE; | |
let mut wav_out = std::fs::File::create("./piano.wav").unwrap(); | |
wav_io::write_to_file(&mut wav_out, &wav_head, &samples).unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment