• Hey! Guest! The 39th GMC Jam will take place between November 26th, 12:00 UTC and November 30th, 12:00 UTC. Why not join in! Click here to find out more!

GML [SOLVED] Trouble writing .wav file into buffer and playing it back

Tzunami

Member
[SOLVED]: buffer_write needed to use buffer_u8 instead of buffer_s16.

Hi all,

I'm having some trouble in a project I'm working on when it comes to opening a .wav file, writing it to a buffer and using 'audio_create_buffer_sound' to play the sound from it. My code successfully opens the .wav file picked from the file browser, but there is something wrong with the way the sound is written to the buffer and it becomes a distorted mess when it is played. Is anybody able to identify what I've done wrong in my code? I've been searching the net for hours and can't find a solution. I asked on the Game Maker Reddit but no one was able to help me there.

The following code is from the mouse pressed event of a GUI button.
GML:
sound = get_open_filename("wav file|*.wav", "");
audio_buff = buffer_create(1024, buffer_grow, 2);

if(file_exists(sound))
{
    file = file_bin_open(sound,0);
    size = file_bin_size(file);

    for(var i = 0; i < size; i++;)
    {
        buffer_write(audio_buff, buffer_s16, file_bin_read_byte(file));
    }
    file_bin_close(file);

    audio = audio_create_buffer_sound(audio_buff, buffer_s16, 48000, 0, size, audio_stereo);
    audio_play_sound(audio, 1, true);
}
I've already tried using buffer_u8 both in the buffer_write and audio_create_buffer_sound and that didn't help, it actually made things even more distorted.
I've also tried using mono instead of stereo and that didn't help either.
I've also played around with the buffer size (making it larger) but to no avail.

Thanks so much in advance if anybody is able to help me!
 
Last edited:

TheouAegis

Member
Are you sure your buffer alignment is correct? What if you change the 2 to a 1? And is the file at least 1024 bytes? Not sure if any extra 0s at the end of the data would have an effect, but it's something I'd consider.
 

Tzunami

Member
Hi TheouAegis,
thanks for the response!

I tried changing the buffer alignment to 1 but it didn't have any affect (the sound was still distorted). The files I am testing it on are all definitely at least 1024 bytes large, although I selected that number fairly arbitrarily, since it's a buffer_grow I could probably make that smaller without many setbacks.
 

TheouAegis

Member
...You're reading the file 8 bits at a time unsigned, but writing 16 bits signed. Change buffer_s16 to buffer_u8 and see if that fixes it. Maybe it's fine in the audio_create part, but for the file reading, you're corrupting the data.
 

Tzunami

Member
Wow that worked! I thought I'd need to use buffer_s16 for both the audio_create_buffer_sound AND the buffer_write, but changing only buffer_write to buffer_u8 worked! Thank you so much!
 
Top