Ratatui Audio with Rodio: Sound FX for Rust Text-based UI
🔊 Adding Sound FX to a Ratatui Game
In this submit, we have a look at Ratatui audio with Rodio. I’ve been constructing a text-based User Interface (TUI) sport in Ratatui. Ratatui is Rust tooling for Terminal apps. This is the third submit within the collection. I wrote the preliminary submit as soon as I had put collectively a minimal viable product, and outlined some subsequent steps in that submit. In the final submit, I added fireworks to the victory display by portray in a Ratatui canvas widget.
As effectively as fireworks, one other enhancement that I recognized (within the first submit) was sound results. I’ve constructed Rust video games with sound earlier than, however relied on the sport’s tooling so as to add handle loading the audio belongings and taking part in them (Macroquad and Bevy, for instance, make this seamless). So, step one was going to be discovering a crate to play MP3 audio. I found Rodio, which labored effectively, and was fast to get going with.
In the remainder of this submit, I discuss concerning the Rodio integration, and a few subsequent steps for the sport. There is a hyperlink to the most recent mission repo, with full code additional down.
🧱 Ratatui Audio with Rodio: What I Built
I didn’t actually need background music, simply sound results to play when the participant begins the problem, after which to supply audio suggestions if their newest answer try was good or good. Finally, I wished to play some audio when every firework on the victory display ignited. I discovered some fairly small wave information for every of those, and transformed them to MP3s.
About Rodio
Rodio makes use of a variety of decrease degree crates below the hood, simplifying including audio by way of their single increased degree API. These, lower-level, crates embody:
-
cpalfor playback; -
symphoniafor MP4 and AAC playback; -
houndfor WAV playback; -
lewtonfor Vorbis playback; and -
claxonfor FLAC playback.
I simply wanted MP3s, so disabled default options, and solely added symphonia-mp3 again within the mission Cargo.toml, to maintain the binary dimension in test:
[package]
identify = "countdown-numbers"
model = "0.1.0"
version = "2021"
license = "BSD-3-Clause"
repository = "https://github.com/rodneylab/countdown-numbers"
# ratatui v0.26.3 requires 1.74.0 or newer
rust-version = "1.74"
description = "Trying Ratatui TUI 🧑🏽🍳 constructing a text-based UI quantity sport within the Terminal 🖥️ in Rust with Ratatui fast mode rendering."
[dependencies]
num_parser = "1.0.2"
rand = "0.8.5"
ratatui = "0.27.0"
rodio = { model = "0.18.1", default-features = false, options = ["symphonia-mp3"] }
🐎 Adding Rodio
The Rodio docs give a few examples for getting going. Those examples learn and decode an ogg file from an area folder inside the mission. This makes makes use of of the Rodio decoder struct, both appending it to a Rodio sink, or taking part in decoder output straight on an output stream. Either method, the audio is decoded and performed right away.
That setup works effectively for longer information, performed as soon as. For the sport, I’ve a number of sound results that may be performed dozens of occasions. It appeared just a little extravagant to learn from a file and decode every time I wanted to play the identical sound impact. Luckily, I discovered a Stack Overflow submit with another strategy, letting you buffer the decoder output. Since the audio information have been no greater that 10 KB, I used to be joyful to buffer them because the app begins up and preserve them in reminiscence.
Rust Code
I created a SoundResults struct for holding all of the sound results, as there are solely 5 of them. For an app with extra, I might try a cleaner answer, however this strategy retains issues easy for what I’ve.
use std::{fs::File, path::Path};
use rodio::{
supply::{Buffered, Source},
Decoder,
};
pub struct SoundResults {
pub begin: Buffered<Decoder<File>>,
pub finish: Buffered<Decoder<File>>,
pub good: Buffered<Decoder<File>>,
pub legitimate: Buffered<Decoder<File>>,
pub firework: Buffered<Decoder<File>>,
}
fn buffer_sound_effect<P: AsRef<Path>>(path: P) -> Buffered<Decoder<File>> {
let sound_file = File::open(&path)
.unwrap_or_else(|_| panic!("Should be capable to load `{}`", path.as_ref().show()));
let supply = Decoder::new(sound_file).unwrap_or_else(|_| {
panic!(
"Should be capable to decode audio file `{}`",
path.as_ref().show()
)
});
supply.buffered()
}
impl Default for SoundResults {
fn default() -> Self {
SoundResults {
begin: buffer_sound_effect("./belongings/begin.mp3"),
finish: buffer_sound_effect("./belongings/finish.mp3"),
good: buffer_sound_effect("./belongings/good.mp3"),
legitimate: buffer_sound_effect("./belongings/legitimate.mp3"),
firework: buffer_sound_effect("./belongings/firework.mp3"),
}
}
}
The default initializer for the SoundResults struct simply creates a buffered decoding for every of the results, which might be referred to as later from the app code.
In app code, I can then clone one among these buffers and add it to a sink to play it. For instance in the principle sport loop:
fn run_app<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> io::Result<()> {
// ...TRUNCATED
let (_stream, stream_handle) = OutputStream::try_default().unwrap();
let sink = Sink::try_new(&stream_handle).unwrap();
let sound_effects = SoundResults::default();
loop {
if occasion::ballot(timeout)? {
if let Event::Key(key) = occasion::learn()? {
// ...TRUNCATED
match app.current_screen {
// ...TRUNCATED
PresentScreen::PickingNumbers => match key.code {
KeyCode::Enter => {
if app.is_number_selection_complete() {
app.current_screen = PresentScreen::Playing;
sink.append(sound_effects.begin.clone());
}
}
}
}
}
}
// TRUNCATED...
}
}
We initialize the sink forward of the principle loop, then play the buffered sound from inside it (line 19), by calling sink.append(). sink.append() pushes the buffer right into a queue and performs it instantly (if nothing is already taking part in), or waits till the final sound has completed earlier than beginning. That setup works right here, and if you want to play sounds concurrently, you may create a number of sinks. This setup additionally avoids borrow checker points with consuming the File struct, which could come up when decoding the File inside the principle loop.
🙌🏽 Ratatui Audio with Rodio: Wrapping Up
In this Ratatui audio with Rodio submit, I briefly ran by way of how I added audio to the Ratatui Countdown sport. In specific, I talked about:
- why I added Rodio;
- why you may buffer Rodio to keep away from borrow checker points in a sport loop; and
- how I buffered MP3 sound FX with Rodio.
I hope you discovered this convenient. As promised, you may get the complete mission code on the Rodney Lab GitHub repo. I might love to listen to from you, if you’re additionally new to Rust sport growth. Do you’ve various sources you discovered helpful? How will you utilize this code in your individual tasks?
🙏🏽 Ratatui Audio with Rodio: Feedback
If you’ve discovered this submit helpful, see hyperlinks under for additional associated content material on this web site. Let me know if there are any methods I can enhance on it. I hope you’ll use the code or starter in your individual tasks. Be certain to share your work on X, giving me a point out, so I can see what you probably did. Finally, make sure you let me know concepts for different quick movies you want to see. Read on to seek out methods to get in contact, additional under. If you’ve discovered this submit helpful, though you may solely afford even a tiny contribution, please think about supporting me by way of Buy me a Coffee.
Finally, be happy to share the submit in your social media accounts for all of your followers who will discover it helpful. As effectively as leaving a remark under, you may get in contact by way of @askRodney on X (beforehand Twitter) and likewise, be part of the #rodney Element Matrix room. Also, see additional methods to get in contact with Rodney Lab. I submit usually on Game Dev in addition to Rust and C++ (amongst different subjects). Also, subscribe to the publication to maintain up-to-date with our newest tasks.
HI-FI News
by way of DEV Community https://dev.to
June 26, 2024 at 08:23PM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT









