1
0
Fork 0
forked from NotAShelf/rogged
rogged/src/audio.c
NotAShelf 0894466532
audio: allocate samples dynamically to avoid share static buffer corruption
Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: I48808e87cf3aea831daff726eb7123a96a6a6964
2026-04-03 15:45:04 +03:00

100 lines
2.3 KiB
C

#include "audio.h"
#include "raylib.h"
#include <math.h>
#include <stddef.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846 // xd
#endif
#define SAMPLE_RATE 44100
#define DURATION 0.1
// Generate a simple sine wave tone
static void play_tone(float frequency, float duration, float volume) {
int sample_count = (int)(SAMPLE_RATE * duration);
if (sample_count > SAMPLE_RATE)
sample_count = SAMPLE_RATE;
if (sample_count <= 0)
return;
// Allocate samples dynamically to avoid shared static buffer corruption
float *samples = (float *)MemAlloc(sample_count * sizeof(float));
if (samples == NULL)
return;
// Generate sine wave
for (int i = 0; i < sample_count; i++) {
float t = (float)i / SAMPLE_RATE;
samples[i] = sinf(2.0f * M_PI * frequency * t) * volume;
// Apply simple envelope (fade in/out)
float envelope = 1.0f;
int fade_samples = SAMPLE_RATE / 20; // 50ms fade
if (i < fade_samples) {
envelope = (float)i / fade_samples;
} else if (i > sample_count - fade_samples) {
envelope = (float)(sample_count - i) / fade_samples;
}
samples[i] *= envelope;
}
// Create wave from samples
Wave wave = {.frameCount = (unsigned int)sample_count,
.sampleRate = SAMPLE_RATE,
.sampleSize = 32,
.channels = 1,
.data = samples};
Sound sound = LoadSoundFromWave(wave);
PlaySound(sound);
UnloadSound(sound);
// Free the dynamically allocated buffer
MemFree(samples);
}
void audio_init(void) {
// Initialize audio device
InitAudioDevice();
}
void audio_close(void) {
// Close audio device
CloseAudioDevice();
}
void audio_play_move(void) {
// Low blip for movement
play_tone(200.0f, 0.05f, 0.3f);
}
void audio_play_attack(void) {
// Mid-range hit sound
play_tone(400.0f, 0.1f, 0.5f);
}
void audio_play_item_pickup(void) {
// High-pitched pickup sound
play_tone(800.0f, 0.15f, 0.4f);
}
void audio_play_enemy_death(void) {
// Descending death sound
play_tone(300.0f, 0.1f, 0.5f);
play_tone(150.0f, 0.15f, 0.4f);
}
void audio_play_player_damage(void) {
// Harsh damage sound
play_tone(150.0f, 0.1f, 0.6f);
play_tone(100.0f, 0.1f, 0.4f);
}
void audio_play_stairs(void) {
// Ascending stairs sound
play_tone(400.0f, 0.1f, 0.3f);
play_tone(600.0f, 0.1f, 0.3f);
play_tone(800.0f, 0.15f, 0.3f);
}