audio: allocate samples dynamically to avoid share static buffer corruption
Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: I48808e87cf3aea831daff726eb7123a96a6a6964
This commit is contained in:
parent
4908a32661
commit
0894466532
1 changed files with 13 additions and 3 deletions
16
src/audio.c
16
src/audio.c
|
|
@ -1,9 +1,10 @@
|
||||||
#include "audio.h"
|
#include "audio.h"
|
||||||
#include "raylib.h"
|
#include "raylib.h"
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
#ifndef M_PI
|
#ifndef M_PI
|
||||||
#define M_PI 3.14159265358979323846 // xd
|
#define M_PI 3.14159265358979323846 // xd
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define SAMPLE_RATE 44100
|
#define SAMPLE_RATE 44100
|
||||||
|
|
@ -11,11 +12,17 @@
|
||||||
|
|
||||||
// Generate a simple sine wave tone
|
// Generate a simple sine wave tone
|
||||||
static void play_tone(float frequency, float duration, float volume) {
|
static void play_tone(float frequency, float duration, float volume) {
|
||||||
static float samples[SAMPLE_RATE];
|
|
||||||
int sample_count = (int)(SAMPLE_RATE * duration);
|
int sample_count = (int)(SAMPLE_RATE * duration);
|
||||||
|
|
||||||
if (sample_count > SAMPLE_RATE)
|
if (sample_count > SAMPLE_RATE)
|
||||||
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
|
// Generate sine wave
|
||||||
for (int i = 0; i < sample_count; i++) {
|
for (int i = 0; i < sample_count; i++) {
|
||||||
|
|
@ -24,7 +31,7 @@ static void play_tone(float frequency, float duration, float volume) {
|
||||||
|
|
||||||
// Apply simple envelope (fade in/out)
|
// Apply simple envelope (fade in/out)
|
||||||
float envelope = 1.0f;
|
float envelope = 1.0f;
|
||||||
int fade_samples = SAMPLE_RATE / 20; // 50ms fade
|
int fade_samples = SAMPLE_RATE / 20; // 50ms fade
|
||||||
if (i < fade_samples) {
|
if (i < fade_samples) {
|
||||||
envelope = (float)i / fade_samples;
|
envelope = (float)i / fade_samples;
|
||||||
} else if (i > sample_count - fade_samples) {
|
} else if (i > sample_count - fade_samples) {
|
||||||
|
|
@ -43,6 +50,9 @@ static void play_tone(float frequency, float duration, float volume) {
|
||||||
Sound sound = LoadSoundFromWave(wave);
|
Sound sound = LoadSoundFromWave(wave);
|
||||||
PlaySound(sound);
|
PlaySound(sound);
|
||||||
UnloadSound(sound);
|
UnloadSound(sound);
|
||||||
|
|
||||||
|
// Free the dynamically allocated buffer
|
||||||
|
MemFree(samples);
|
||||||
}
|
}
|
||||||
|
|
||||||
void audio_init(void) {
|
void audio_init(void) {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue