Skip to main content

silence_split/
lib.rs

1//! Split long PCM audio into pieces that never exceed a maximum length, cutting in silence, or at
2//! the quietest spot when there is none. No model, no FFmpeg, and every position is a sample index
3//! in the original timeline.
4//!
5//! 1. [`Analyzer`] turns PCM of any sample rate into frame levels ([`Analysis`]). Scores from an
6//!    external voice activity detector can be used instead with [`Analysis::from_scores`].
7//! 2. [`Analysis::segments`] finds silence and sound, and [`Analysis::trim`] the audio between the
8//!    first and last sound.
9//! 3. [`plan`] chooses cuts over the whole file under minimum, target and maximum piece lengths.
10//!    [`adjust`] instead moves cut points you already have into nearby silence.
11//!
12//! ```
13//! use core::time::Duration;
14//! use silence_split::{AnalyzeConfig, Analyzer, Gap, Layout, PlanConfig, SegmentConfig, plan};
15//!
16//! # fn main() -> Result<(), silence_split::ConfigError> {
17//! let layout = Layout { sample_rate: 16_000, channels: 1 };
18//! let mut analyzer = Analyzer::new(layout, &AnalyzeConfig::default())?;
19//! # let pcm: Vec<f32> = (0..16_000 * 20)
20//! #     .map(|i| if (i / 16_000) % 5 == 4 { 0.0 } else { 0.3 * (i as f32 * 0.07).sin() })
21//! #     .collect();
22//! analyzer.push_interleaved(&pcm);
23//! let analysis = analyzer.finish();
24//!
25//! let config = PlanConfig::new(Duration::from_secs(2), Duration::from_secs(8), Duration::from_secs(10))?
26//!     .gap(Gap::Drop);
27//! let plan = plan(&analysis, &SegmentConfig::default(), &config);
28//! for piece in &plan.pieces {
29//!     let _samples = &pcm[piece.start as usize..piece.end as usize];
30//!     assert!(piece.end - piece.start <= 160_000);
31//! }
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! # Features
37//!
38//! - `std` (default): uses the standard library's floating-point functions. Without it the crate
39//!   is `no_std` with `alloc` and needs the `libm` feature.
40//! - `libm`: floating-point functions for `no_std`.
41//! - `serde`: `Serialize` and `Deserialize` for [`Analysis`], [`Plan`] and the result types.
42//!   Deserializing an [`Analysis`] validates it.
43
44#![no_std]
45
46extern crate alloc;
47#[cfg(feature = "std")]
48extern crate std;
49
50#[cfg(not(any(feature = "std", feature = "libm")))]
51compile_error!("silence-split needs the `std` or the `libm` feature");
52
53mod analyze;
54mod candidates;
55mod dp;
56mod errors;
57mod filter;
58mod labels;
59mod math;
60mod plan;
61mod sample;
62mod segment;
63
64pub use analyze::{Analysis, AnalyzeConfig, Analyzer};
65pub use errors::ConfigError;
66pub use labels::write_audacity_labels;
67pub use plan::{Cut, CutReason, Gap, Piece, Placement, Plan, PlanConfig, Weights, adjust, plan};
68pub use sample::{Layout, Sample};
69pub use segment::{Kind, SegmentConfig, Span, Threshold};
70
71#[cfg(doctest)]
72#[doc = include_str!("../README.md")]
73struct ReadmeDoctests;