use std::{
fs::{File, OpenOptions},
io::BufWriter,
time::Instant,
};
use hound::{SampleFormat, WavSpec, WavWriter};
use piper1_rs::{Piper, PiperAudioChunk};
const OUTPUT_FILE_SPEC: WavSpec = WavSpec {
channels: 1,
sample_rate: 16000,
bits_per_sample: 32,
sample_format: SampleFormat::Float,
};
fn main() {
let mut piper = {
let st = Instant::now();
let piper = Piper::new(
"/path/to/piper-voices/en/en_US/libritts/high/en_US-libritts-high.onnx",
None::<&str>, "/usr/share/espeak-ng-data",
)
.expect("failed to create piper object");
let et = Instant::now();
println!("took {:?} to load piper model", et.duration_since(st));
piper
};
let synth_opts = piper.get_default_synthesis_options();
let mut handle = piper
.start_synthesis("Hi there! I'm here to test Piper!".to_string(), &synth_opts)
.expect("failed to start synthesis");
let st_first = Instant::now();
let first_segment = handle
.get_next_chunk()
.expect("failed to get first chunk")
.expect("there should be at least one chunk");
let et_first = Instant::now();
let mut output_spec = OUTPUT_FILE_SPEC;
output_spec.sample_rate = first_segment.sample_rate();
let mut total_time = et_first.duration_since(st_first);
let file_handle = OpenOptions::new()
.write(true)
.create(true)
.open("output.wav")
.expect("failed to open output file");
let buf_writer = BufWriter::new(file_handle);
let mut writer = WavWriter::new(buf_writer, output_spec).expect("failed to create WavWriter");
let mut file_duration = 0.0;
file_duration += write_sample(&first_segment, &mut writer);
let mut segment;
loop {
let st = Instant::now();
segment = handle.get_next_chunk().expect("failed to get next segment");
let et = Instant::now();
total_time += et.duration_since(st);
let Some(segment) = segment else {
break;
};
file_duration += write_sample(&segment, &mut writer);
}
writer.finalize().expect("failed to finalize output");
let total_time_f64 = total_time.as_secs_f64();
let rtf = total_time_f64 / file_duration;
println!(
"took {:?} to synthesize {}s audio file (RTF = {}, inverse = {})",
total_time,
file_duration,
rtf,
rtf.powi(-1)
)
}
fn write_sample(chunk: &PiperAudioChunk, writer: &mut WavWriter<BufWriter<File>>) -> f64 {
let num_samples = chunk.num_samples();
let sample_rate = chunk.sample_rate();
assert_eq!(sample_rate, writer.spec().sample_rate);
let segment_duration = num_samples as f64 / sample_rate as f64;
println!(
"got a segment with {} samples at {}Hz, for a time of {}s",
num_samples, sample_rate, segment_duration
);
for s in chunk.samples() {
writer.write_sample(*s).expect("failed to write");
}
segment_duration
}