Skip to content

Instantly share code, notes, and snippets.

@bartteunis
Last active September 4, 2021 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bartteunis/0f18f37afc7bb2d6bd4526d86b5dea04 to your computer and use it in GitHub Desktop.
Save bartteunis/0f18f37afc7bb2d6bd4526d86b5dea04 to your computer and use it in GitHub Desktop.
/// @description Load WAV file
function wav(path) constructor {
read_chunk_id_size = function(buffer) {
var _id = "";
repeat(4) { _id += chr(buffer_read(buffer, buffer_u8)); }
var _size = buffer_read(buffer, buffer_u32);
return [_id, _size];
}
buff = buffer_load(path);
// Read all chunks
while !(buffer_tell(buff) >= buffer_get_size(buff) - 1) {
// Read subchunk
var sc_id_size = read_chunk_id_size(buff);
switch sc_id_size[0] {
case "RIFF":
// RIFF header
// See: https://www.recordingblogs.com/wiki/wave-file-format
if (sc_id_size[0] != "RIFF") { exit; }
var temp = buffer_read(buff, buffer_u32) == 0x45564157; // "WAVE"
break;
case "fmt ":
// WAV format
// See: https://www.recordingblogs.com/wiki/format-chunk-of-a-wave-file
format = {};
format.compression_code = buffer_read(buff, buffer_u16);
format.num_channels = buffer_read(buff, buffer_u16);
format.sample_rate = buffer_read(buff, buffer_u32);
format.byte_rate = buffer_read(buff, buffer_u32);
format.block_align = buffer_read(buff, buffer_u16);
format.bits_per_sample = buffer_read(buff, buffer_u16);
break;
case "data":
// Audio data
// See: https://www.recordingblogs.com/wiki/data-chunk-of-a-wave-file
// Simply store current pointer position and size here
var pos = buffer_tell(buff);
offset_length = [pos, sc_id_size[1]];
buffer_seek(buff, buffer_seek_relative, sc_id_size[1]);
break;
default:
// Skip chunk entirely
buffer_seek(buff, buffer_seek_relative, sc_id_size[1]);
}
}
free = function() {
// Frees the buffer and buffer sound
audio_free_buffer_sound(sound);
buffer_delete(buff);
}
get_sound = function() {
if (format.compression_code != 1) { exit; } // It's compressed...
if (format.bits_per_sample > 16) { exit; } // Either 8 or 16
if (format.num_channels > 2) { exit; } // Too many channels
var sound = audio_create_buffer_sound(buff,
format.bits_per_sample == 8 ? buffer_u8 : buffer_s16,
format.sample_rate,
offset_length[0], offset_length[1],
format.num_channels == 1 ? audio_mono : audio_stereo
);
return sound;
}
}
test = new wav("test.wav");
show_debug_message(test.format);
audio_play_sound(test.get_sound(), 0, true);
//test.free();
//delete test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment