piper1-rs 0.1.0

Safe Rust bindings to Piper, the TTS library
Documentation
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() {
	// Load a piper model
	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>, // specify any type that implements Into<String> here
			"/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
	};

	// Build default options
	let synth_opts = piper.get_default_synthesis_options();

	// Build a handle that will be used to get synthesized segments
	let mut handle = piper
		.start_synthesis("Hi there! I'm here to test Piper!".to_string(), &synth_opts)
		.expect("failed to start synthesis");

	// we can only get the output sample rate after we have a chunk
	// as awkward as this is it seems to be a limitation of piper
	// because the C API offers no way to obtain sample rate
	// before having a chunk
	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();

	// calculate how long it takes that way we have a RTF later
	let mut total_time = et_first.duration_since(st_first);

	// open the output file
	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;

	// write our first chunk
	file_duration += write_sample(&first_segment, &mut writer);

	// and enter a loop for more chunks
	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
}