1. 34
  1. 8

    Neat! Just a couple of very minor notes on the implementation. As it’s a relatively straightforward program, it’s already pretty close to idiomatic Zig.

    I’ve implemented a simple little set of helper functions to write u32 and u64 to the output. I believe there are better ways to do that, but this works fine. Much of this is really pretty close to the rust source, maybe surprisingly so.

    Yep! Zig’s Writer interface has writeIntLittle and writeIntBig methods. Internally they’re implemented similarly to yours.

    try write_u32(HEADER_SIZE + numsamples, file);
    // instead:
    try file.writeIntLittle(u32, HEADER_SIZE + numsamples); 

    You also probably want to use writeAll rather than write, as write isn’t guaranteed to write every byte to the file; it returns the number of bytes written (a value that your code ignores).

    _ = try file.write("RIFF"); // may truncate
    try file.writeAll("RIFF"); // won't truncate unless there's an error

    Finally, it’s better practice to use defer to cleanup resources, rather than closing them at the end of the function. This guarantees that they’ll be cleaned up even if an early return occurs (such as if try fails).

    var file = try cwd.createFile("sine.wav", .{});
    defer _ = file.close();
    try write_header(3, file);
    try sine_wave(3, file, 440.0);
    1. 10

      These and a few other suggestions were nicely written up by xq here: https://zig.news/xq/re-makin-wavs-with-zig-1jjd

      1. 2

        Some nice suggestions there that I missed!