summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/zeal.zig50
1 files changed, 35 insertions, 15 deletions
diff --git a/src/zeal.zig b/src/zeal.zig
index d73c674..26dffa8 100644
--- a/src/zeal.zig
+++ b/src/zeal.zig
@@ -18,11 +18,12 @@
 
 const Allocator = std.mem.Allocator;
 const SndFile = sf.SndFile;
-pub const al = @import("al.zig");
-pub const alc = @import("alc.zig");
 const sf = @import("sf.zig");
 const std = @import("std");
 
+pub const al = @import("al.zig");
+pub const alc = @import("alc.zig");
+
 pub const Error = al.Error || error {
     UncurrentContext,
 };
@@ -89,25 +90,44 @@ pub const Listener = struct {
     }
 };
 
+pub const Audio = struct {
+    allocator: *Allocator,
+    data: al.Data,
+    frequency: i32,
+
+    /// Read audio from file.
+    pub fn read(allocator: *Allocator, path: [:0]const u8) sf.Error!Audio {
+        const sound = try SndFile.open(path, sf.Mode.read);
+        defer sound.close();
+        const data = try sound.readAll(allocator);
+        return Audio {
+            .allocator = allocator,
+            .data = switch (sound.channels) {
+                1 => al.Data{ .mono16 = data },
+                2 => al.Data{ .stereo16 = data },
+                else => unreachable,
+            },
+            .frequency = sound.sample_rate,
+        };
+    }
+
+    /// Free allocated memory.
+    pub fn free(self: Audio) void {
+        switch (self.data) {
+            .mono8, .stereo8 => |data| self.allocator.free(data),
+            .mono16, .stereo16 => |data| self.allocator.free(data),
+        }
+    }
+};
+
 pub const Buffer = struct {
     context: Context,
     reference: u32,
 
-    pub fn init(allocator: *Allocator, context: Context,
-                name: [:0]const u8) (Error || sf.Error)!Buffer {
+    pub fn init(context: Context, audio: Audio) Error!Buffer {
         try checkContext(context);
-        const snd_file = try SndFile.open(name, sf.Mode.read);
-        defer snd_file.close();
-        const data = try snd_file.readAll(allocator);
-        defer allocator.free(data);
-        const al_data = switch (snd_file.channels) {
-            1 => al.Data{ .mono16 = data },
-            2 => al.Data{ .stereo16 = data },
-            else => unreachable,
-        };
-
         const reference = try al.buffer.create();
-        try al.buffer.fill(reference, al_data, snd_file.sample_rate);
+        try al.buffer.fill(reference, audio.data, audio.frequency);
         return Buffer{ .context = context, .reference = reference };
     }