DEV Community

Ben Santora
Ben Santora

Posted on

Rust - Simple Wave Generator

Here's a step-by-step method for Rust beginners to create a simple audio wave generator project. This guide includes all the essential steps.
NOTE: This method uses the Linux terminal - if you're on Windows 10, you can use WSL.

  1. Install Rust and Cargo Before starting, ensure you have Rust and Cargo installed. If not, you can install Rust using the following command:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Follow the instructions to complete the installation. This also installs Cargo, Rust's package manager and build tool.

  1. Create a New Rust Project Using Cargo

To create a new Rust project, open your terminal and run:

cargo new wave_gen --bin

(The --bin flag when running cargo new specifies that you want to create a binary (executable) project, meaning the project will produce an executable file when built.)

This creates a directory called wave_gen with the following structure:

wave_gen/
├── Cargo.toml
└── src
└── main.rs
• Cargo.toml is the file where dependencies are declared.
• src/main.rs is the main Rust file for the project.

  1. Add the hound Dependency to Cargo.toml

Open the Cargo.toml file and add the hound crate to the [dependencies] section. This crate allows us to create and manipulate WAV files. Edit Cargo.toml (nano or your favorite text editor) as follows:

[dependencies]
hound = "3.4"

This tells Cargo to download the hound crate when building the project. (Internet connection required for first time.)

  1. Edit src/main.rs Next, replace the contents of src/main.rs with the following Rust code. This code generates a sine wave and saves it as a .wav file.
use hound;
use std::f32::consts::PI;
use std::fs;

fn main() {
    // Parameters for the sine wave
    let sample_rate = 44100;
    let duration = 2.0;  // Duration in seconds
    let frequency = 220.0;  // Frequency of the sine wave in Hz
    let amplitude = 0.5;  // Amplitude

    // Ensure the "output" directory exists
    fs::create_dir_all("./output").unwrap();

    // Create a WAV file writer
    let spec = hound::WavSpec {
        channels: 1,
        sample_rate: sample_rate,
        bits_per_sample: 16,
        sample_format: hound::SampleFormat::Int,
    };

    let mut writer = hound::WavWriter::create("./output/audio220.wav", spec).unwrap();

    // Generate the sine wave samples
    let samples = (0..(sample_rate as f32 * duration) as u32).map(|x| {
        let t = x as f32 / sample_rate as f32;
        let sample = (amplitude * (2.0 * PI * frequency * t).sin()) as f32;
        (sample * i16::MAX as f32) as i16
    });

    // Write the samples to the WAV file
    for sample in samples {
        writer.write_sample(sample).unwrap();
    }

    writer.finalize().unwrap();
}
Enter fullscreen mode Exit fullscreen mode
  1. Build the Project After editing main.rs and adding the hound dependency, you can now build the project. In your terminal, run:

cargo build

This will compile the project, download the hound crate, and handle all dependencies.

  1. Run the Program Once the build is successful, you can run the program using:

cargo run

This will generate a .wav file called audio220.wav in the output directory. The file will contain a 2-second sine wave at 220 Hz.

  1. Optional: Clean Up the Build Artifacts Cargo creates several build artifacts and dependencies. If you want to clean them up, you can run:

cargo clean

Let me know if you'd like further clarification or refinements!

Ben Santora - October 2024

Top comments (0)