1 /**********************************************************************************************
3 * raudio v1.0 - A simple and easy-to-use audio library based on miniaudio
6 * - Manage audio device (init/close)
7 * - Manage raw audio context
8 * - Manage mixing channels
9 * - Load and unload audio files
10 * - Format wave data (sample rate, size, channels)
11 * - Play/Stop/Pause/Resume loaded audio
15 * #define RAUDIO_STANDALONE
16 * Define to use the module as standalone library (independently of raylib).
17 * Required types and functions are defined in the same module.
19 * #define SUPPORT_FILEFORMAT_WAV
20 * #define SUPPORT_FILEFORMAT_OGG
21 * #define SUPPORT_FILEFORMAT_XM
22 * #define SUPPORT_FILEFORMAT_MOD
23 * #define SUPPORT_FILEFORMAT_FLAC
24 * #define SUPPORT_FILEFORMAT_MP3
25 * Selected desired fileformats to be supported for loading. Some of those formats are
26 * supported by default, to remove support, just comment unrequired #define in this module
29 * miniaudio.h - Audio device management lib (https://github.com/dr-soft/miniaudio)
30 * stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/)
31 * dr_mp3.h - MP3 audio file loading (https://github.com/mackron/dr_libs)
32 * dr_flac.h - FLAC audio file loading (https://github.com/mackron/dr_libs)
33 * jar_xm.h - XM module file loading
34 * jar_mod.h - MOD audio file loading
37 * David Reid (github: @mackron) (Nov. 2017):
38 * - Complete port to miniaudio library
40 * Joshua Reisenauer (github: @kd7tck) (2015)
41 * - XM audio module support (jar_xm)
42 * - MOD audio module support (jar_mod)
43 * - Mixing channels support
44 * - Raw audio context support
47 * LICENSE: zlib/libpng
49 * Copyright (c) 2013-2021 Ramon Santamaria (@raysan5)
51 * This software is provided "as-is", without any express or implied warranty. In no event
52 * will the authors be held liable for any damages arising from the use of this software.
54 * Permission is granted to anyone to use this software for any purpose, including commercial
55 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
57 * 1. The origin of this software must not be misrepresented; you must not claim that you
58 * wrote the original software. If you use this software in a product, an acknowledgment
59 * in the product documentation would be appreciated but is not required.
61 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
62 * as being the original software.
64 * 3. This notice may not be removed or altered from any source distribution.
66 **********************************************************************************************/
68 #if defined(RAUDIO_STANDALONE)
70 #include <stdarg.h> // Required for: va_list, va_start(), vfprintf(), va_end()
72 #include "raylib.h" // Declares module functions
74 // Check if config flags have been externally provided on compilation line
75 #if !defined(EXTERNAL_CONFIG_FLAGS)
76 #include "config.h" // Defines module configuration flags
78 #include "utils.h" // Required for: fopen() Android mapping
82 // To avoid conflicting windows.h symbols with raylib, some flags are defined
83 // WARNING: Those flags avoid inclusion of some Win32 headers that could be required
84 // by user at some point and won't be included...
85 //-------------------------------------------------------------------------------------
87 // If defined, the following flags inhibit definition of the indicated items.
88 #define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_
89 #define NOVIRTUALKEYCODES // VK_*
90 #define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_*
91 #define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_*
92 #define NOSYSMETRICS // SM_*
93 #define NOMENUS // MF_*
94 #define NOICONS // IDI_*
95 #define NOKEYSTATES // MK_*
96 #define NOSYSCOMMANDS // SC_*
97 #define NORASTEROPS // Binary and Tertiary raster ops
98 #define NOSHOWWINDOW // SW_*
99 #define OEMRESOURCE // OEM Resource values
100 #define NOATOM // Atom Manager routines
101 #define NOCLIPBOARD // Clipboard routines
102 #define NOCOLOR // Screen colors
103 #define NOCTLMGR // Control and Dialog routines
104 #define NODRAWTEXT // DrawText() and DT_*
105 #define NOGDI // All GDI defines and routines
106 #define NOKERNEL // All KERNEL defines and routines
107 #define NOUSER // All USER defines and routines
108 //#define NONLS // All NLS defines and routines
109 #define NOMB // MB_* and MessageBox()
110 #define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines
111 #define NOMETAFILE // typedef METAFILEPICT
112 #define NOMINMAX // Macros min(a,b) and max(a,b)
113 #define NOMSG // typedef MSG and associated routines
114 #define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_*
115 #define NOSCROLL // SB_* and scrolling routines
116 #define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc.
117 #define NOSOUND // Sound driver routines
118 #define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines
119 #define NOWH // SetWindowsHook and WH_*
120 #define NOWINOFFSETS // GWL_*, GCL_*, associated routines
121 #define NOCOMM // COMM driver routines
122 #define NOKANJI // Kanji support stuff.
123 #define NOHELP // Help engine interface.
124 #define NOPROFILER // Profiler interface.
125 #define NODEFERWINDOWPOS // DeferWindowPos routines
126 #define NOMCX // Modem Configuration Extensions
128 // Type required before windows.h inclusion
129 typedef struct tagMSG *LPMSG;
133 // Type required by some unused function...
134 typedef struct tagBITMAPINFOHEADER {
142 LONG biXPelsPerMeter;
143 LONG biYPelsPerMeter;
145 DWORD biClrImportant;
146 } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
150 #include <mmsystem.h>
152 // Some required types defined for MSVC/TinyC compiler
153 #if defined(_MSC_VER) || defined(__TINYC__)
158 #define MA_MALLOC RL_MALLOC
159 #define MA_FREE RL_FREE
165 #define MINIAUDIO_IMPLEMENTATION
166 //#define MA_DEBUG_OUTPUT
167 #include "external/miniaudio.h" // miniaudio library
168 #undef PlaySound // Win32 API: windows.h > mmsystem.h defines PlaySound macro
170 #include <stdlib.h> // Required for: malloc(), free()
171 #include <stdio.h> // Required for: FILE, fopen(), fclose(), fread()
173 #if defined(RAUDIO_STANDALONE)
174 #include <string.h> // Required for: strcmp() [Used in IsFileExtension()]
176 #if !defined(TRACELOG)
177 #define TRACELOG(level, ...) (void)0
180 // Allow custom memory allocators
182 #define RL_MALLOC(sz) malloc(sz)
185 #define RL_CALLOC(n,sz) calloc(n,sz)
188 #define RL_REALLOC(ptr,sz) realloc(ptr,sz)
191 #define RL_FREE(ptr) free(ptr)
195 #if defined(SUPPORT_FILEFORMAT_OGG)
196 // TODO: Remap malloc()/free() calls to RL_MALLOC/RL_FREE
198 #define STB_VORBIS_IMPLEMENTATION
199 #include "external/stb_vorbis.h" // OGG loading functions
202 #if defined(SUPPORT_FILEFORMAT_XM)
203 #define JARXM_MALLOC RL_MALLOC
204 #define JARXM_FREE RL_FREE
206 #define JAR_XM_IMPLEMENTATION
207 #include "external/jar_xm.h" // XM loading functions
210 #if defined(SUPPORT_FILEFORMAT_MOD)
211 #define JARMOD_MALLOC RL_MALLOC
212 #define JARMOD_FREE RL_FREE
214 #define JAR_MOD_IMPLEMENTATION
215 #include "external/jar_mod.h" // MOD loading functions
218 #if defined(SUPPORT_FILEFORMAT_WAV)
219 #define DRWAV_MALLOC RL_MALLOC
220 #define DRWAV_REALLOC RL_REALLOC
221 #define DRWAV_FREE RL_FREE
223 #define DR_WAV_IMPLEMENTATION
224 #include "external/dr_wav.h" // WAV loading functions
227 #if defined(SUPPORT_FILEFORMAT_MP3)
228 #define DRMP3_MALLOC RL_MALLOC
229 #define DRMP3_REALLOC RL_REALLOC
230 #define DRMP3_FREE RL_FREE
232 #define DR_MP3_IMPLEMENTATION
233 #include "external/dr_mp3.h" // MP3 loading functions
236 #if defined(SUPPORT_FILEFORMAT_FLAC)
237 #define DRFLAC_MALLOC RL_MALLOC
238 #define DRFLAC_REALLOC RL_REALLOC
239 #define DRFLAC_FREE RL_FREE
241 #define DR_FLAC_IMPLEMENTATION
242 #define DR_FLAC_NO_WIN32_IO
243 #include "external/dr_flac.h" // FLAC loading functions
246 #if defined(_MSC_VER)
250 //----------------------------------------------------------------------------------
251 // Defines and Macros
252 //----------------------------------------------------------------------------------
253 #ifndef AUDIO_DEVICE_FORMAT
254 #define AUDIO_DEVICE_FORMAT ma_format_f32 // Device output format (float-32bit)
256 #ifndef AUDIO_DEVICE_CHANNELS
257 #define AUDIO_DEVICE_CHANNELS 2 // Device output channels: stereo
260 #ifndef AUDIO_DEVICE_SAMPLE_RATE
261 #define AUDIO_DEVICE_SAMPLE_RATE 0 // Device output channels: stereo
263 #ifndef MAX_AUDIO_BUFFER_POOL_CHANNELS
264 #define MAX_AUDIO_BUFFER_POOL_CHANNELS 16 // Audio pool channels
266 #ifndef DEFAULT_AUDIO_BUFFER_SIZE
267 #define DEFAULT_AUDIO_BUFFER_SIZE 4096 // Default audio buffer size
271 //----------------------------------------------------------------------------------
272 // Types and Structures Definition
273 //----------------------------------------------------------------------------------
275 // Music context type
276 // NOTE: Depends on data structure provided by the library
277 // in charge of reading the different file types
279 MUSIC_AUDIO_NONE = 0,
288 #if defined(RAUDIO_STANDALONE)
301 // NOTE: Different logic is used when feeding data to the playback device
302 // depending on whether or not data is streamed (Music vs Sound)
304 AUDIO_BUFFER_USAGE_STATIC = 0,
305 AUDIO_BUFFER_USAGE_STREAM
308 // Audio buffer structure
309 struct rAudioBuffer {
310 ma_data_converter converter; // Audio data converter
312 float volume; // Audio buffer volume
313 float pitch; // Audio buffer pitch
315 bool playing; // Audio buffer state: AUDIO_PLAYING
316 bool paused; // Audio buffer state: AUDIO_PAUSED
317 bool looping; // Audio buffer looping, always true for AudioStreams
318 int usage; // Audio buffer usage mode: STATIC or STREAM
320 bool isSubBufferProcessed[2]; // SubBuffer processed (virtual double buffer)
321 unsigned int sizeInFrames; // Total buffer size in frames
322 unsigned int frameCursorPos; // Frame cursor position
323 unsigned int totalFramesProcessed; // Total frames processed in this buffer (required for play timing)
325 unsigned char *data; // Data buffer, on music stream keeps filling
327 rAudioBuffer *next; // Next audio buffer on the list
328 rAudioBuffer *prev; // Previous audio buffer on the list
331 #define AudioBuffer rAudioBuffer // HACK: To avoid CoreAudio (macOS) symbol collision
333 // Audio data context
334 typedef struct AudioData {
336 ma_context context; // miniaudio context data
337 ma_device device; // miniaudio device
338 ma_mutex lock; // miniaudio mutex lock
339 bool isReady; // Check if audio device is ready
342 AudioBuffer *first; // Pointer to first AudioBuffer in the list
343 AudioBuffer *last; // Pointer to last AudioBuffer in the list
344 int defaultSize; // Default audio buffer size for audio streams
347 unsigned int poolCounter; // AudioBuffer pointers pool counter
348 AudioBuffer *pool[MAX_AUDIO_BUFFER_POOL_CHANNELS]; // Multichannel AudioBuffer pointers pool
349 unsigned int channels[MAX_AUDIO_BUFFER_POOL_CHANNELS]; // AudioBuffer pool channels
353 //----------------------------------------------------------------------------------
354 // Global Variables Definition
355 //----------------------------------------------------------------------------------
356 static AudioData AUDIO = { // Global AUDIO context
358 // NOTE: Music buffer size is defined by number of samples, independent of sample size and channels number
359 // After some math, considering a sampleRate of 48000, a buffer refill rate of 1/60 seconds and a
360 // standard double-buffering system, a 4096 samples buffer has been chosen, it should be enough
361 // In case of music-stalls, just increase this number
362 .Buffer.defaultSize = 0
365 //----------------------------------------------------------------------------------
366 // Module specific Functions Declaration
367 //----------------------------------------------------------------------------------
368 static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message);
369 static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount);
370 static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume);
372 #if defined(SUPPORT_FILEFORMAT_WAV)
373 static Wave LoadWAV(const unsigned char *fileData, unsigned int fileSize); // Load WAV file
374 static int SaveWAV(Wave wave, const char *fileName); // Save wave data as WAV file
376 #if defined(SUPPORT_FILEFORMAT_OGG)
377 static Wave LoadOGG(const unsigned char *fileData, unsigned int fileSize); // Load OGG file
379 #if defined(SUPPORT_FILEFORMAT_FLAC)
380 static Wave LoadFLAC(const unsigned char *fileData, unsigned int fileSize); // Load FLAC file
382 #if defined(SUPPORT_FILEFORMAT_MP3)
383 static Wave LoadMP3(const unsigned char *fileData, unsigned int fileSize); // Load MP3 file
386 #if defined(RAUDIO_STANDALONE)
387 static bool IsFileExtension(const char *fileName, const char *ext); // Check file extension
388 static unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead); // Load file data as byte array (read)
389 static bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite); // Save data to file from byte array (write)
390 static bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated
393 //----------------------------------------------------------------------------------
394 // AudioBuffer management functions declaration
395 // NOTE: Those functions are not exposed by raylib... for the moment
396 //----------------------------------------------------------------------------------
397 AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 sizeInFrames, int usage);
398 void UnloadAudioBuffer(AudioBuffer *buffer);
400 bool IsAudioBufferPlaying(AudioBuffer *buffer);
401 void PlayAudioBuffer(AudioBuffer *buffer);
402 void StopAudioBuffer(AudioBuffer *buffer);
403 void PauseAudioBuffer(AudioBuffer *buffer);
404 void ResumeAudioBuffer(AudioBuffer *buffer);
405 void SetAudioBufferVolume(AudioBuffer *buffer, float volume);
406 void SetAudioBufferPitch(AudioBuffer *buffer, float pitch);
407 void TrackAudioBuffer(AudioBuffer *buffer);
408 void UntrackAudioBuffer(AudioBuffer *buffer);
409 int GetAudioStreamBufferSizeDefault();
411 //----------------------------------------------------------------------------------
412 // Module Functions Definition - Audio Device initialization and Closing
413 //----------------------------------------------------------------------------------
414 // Initialize audio device
415 void InitAudioDevice(void)
417 // TODO: Load AUDIO context memory dynamically?
419 // Init audio context
420 ma_context_config ctxConfig = ma_context_config_init();
421 ctxConfig.logCallback = OnLog;
423 ma_result result = ma_context_init(NULL, 0, &ctxConfig, &AUDIO.System.context);
424 if (result != MA_SUCCESS)
426 TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize context");
431 // NOTE: Using the default device. Format is floating point because it simplifies mixing.
432 ma_device_config config = ma_device_config_init(ma_device_type_playback);
433 config.playback.pDeviceID = NULL; // NULL for the default playback AUDIO.System.device.
434 config.playback.format = AUDIO_DEVICE_FORMAT;
435 config.playback.channels = AUDIO_DEVICE_CHANNELS;
436 config.capture.pDeviceID = NULL; // NULL for the default capture AUDIO.System.device.
437 config.capture.format = ma_format_s16;
438 config.capture.channels = 1;
439 config.sampleRate = AUDIO_DEVICE_SAMPLE_RATE;
440 config.dataCallback = OnSendAudioDataToDevice;
441 config.pUserData = NULL;
443 result = ma_device_init(&AUDIO.System.context, &config, &AUDIO.System.device);
444 if (result != MA_SUCCESS)
446 TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize playback device");
447 ma_context_uninit(&AUDIO.System.context);
451 // Keep the device running the whole time. May want to consider doing something a bit smarter and only have the device running
452 // while there's at least one sound being played.
453 result = ma_device_start(&AUDIO.System.device);
454 if (result != MA_SUCCESS)
456 TRACELOG(LOG_WARNING, "AUDIO: Failed to start playback device");
457 ma_device_uninit(&AUDIO.System.device);
458 ma_context_uninit(&AUDIO.System.context);
462 // Mixing happens on a seperate thread which means we need to synchronize. I'm using a mutex here to make things simple, but may
463 // want to look at something a bit smarter later on to keep everything real-time, if that's necessary.
464 if (ma_mutex_init(&AUDIO.System.lock) != MA_SUCCESS)
466 TRACELOG(LOG_WARNING, "AUDIO: Failed to create mutex for mixing");
467 ma_device_uninit(&AUDIO.System.device);
468 ma_context_uninit(&AUDIO.System.context);
472 // Init dummy audio buffers pool for multichannel sound playing
473 for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
475 // WARNING: An empty audioBuffer is created (data = 0)
476 // AudioBuffer data just points to loaded sound data
477 AUDIO.MultiChannel.pool[i] = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC);
480 TRACELOG(LOG_INFO, "AUDIO: Device initialized successfully");
481 TRACELOG(LOG_INFO, " > Backend: miniaudio / %s", ma_get_backend_name(AUDIO.System.context.backend));
482 TRACELOG(LOG_INFO, " > Format: %s -> %s", ma_get_format_name(AUDIO.System.device.playback.format), ma_get_format_name(AUDIO.System.device.playback.internalFormat));
483 TRACELOG(LOG_INFO, " > Channels: %d -> %d", AUDIO.System.device.playback.channels, AUDIO.System.device.playback.internalChannels);
484 TRACELOG(LOG_INFO, " > Sample rate: %d -> %d", AUDIO.System.device.sampleRate, AUDIO.System.device.playback.internalSampleRate);
485 TRACELOG(LOG_INFO, " > Periods size: %d", AUDIO.System.device.playback.internalPeriodSizeInFrames*AUDIO.System.device.playback.internalPeriods);
487 AUDIO.System.isReady = true;
490 // Close the audio device for all contexts
491 void CloseAudioDevice(void)
493 if (AUDIO.System.isReady)
495 // Unload dummy audio buffers pool
496 // WARNING: They can be pointing to already unloaded data
497 for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
499 //UnloadAudioBuffer(AUDIO.MultiChannel.pool[i]);
500 if (AUDIO.MultiChannel.pool[i] != NULL)
502 ma_data_converter_uninit(&AUDIO.MultiChannel.pool[i]->converter);
503 UntrackAudioBuffer(AUDIO.MultiChannel.pool[i]);
504 //RL_FREE(buffer->data); // Already unloaded by UnloadSound()
505 RL_FREE(AUDIO.MultiChannel.pool[i]);
509 ma_mutex_uninit(&AUDIO.System.lock);
510 ma_device_uninit(&AUDIO.System.device);
511 ma_context_uninit(&AUDIO.System.context);
513 AUDIO.System.isReady = false;
515 TRACELOG(LOG_INFO, "AUDIO: Device closed successfully");
517 else TRACELOG(LOG_WARNING, "AUDIO: Device could not be closed, not currently initialized");
520 // Check if device has been initialized successfully
521 bool IsAudioDeviceReady(void)
523 return AUDIO.System.isReady;
526 // Set master volume (listener)
527 void SetMasterVolume(float volume)
529 ma_device_set_master_volume(&AUDIO.System.device, volume);
532 //----------------------------------------------------------------------------------
533 // Module Functions Definition - Audio Buffer management
534 //----------------------------------------------------------------------------------
536 // Initialize a new audio buffer (filled with silence)
537 AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 sizeInFrames, int usage)
539 AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(1, sizeof(AudioBuffer));
541 if (audioBuffer == NULL)
543 TRACELOG(LOG_WARNING, "AUDIO: Failed to allocate memory for buffer");
547 if (sizeInFrames > 0) audioBuffer->data = RL_CALLOC(sizeInFrames*channels*ma_get_bytes_per_sample(format), 1);
549 // Audio data runs through a format converter
550 ma_data_converter_config converterConfig = ma_data_converter_config_init(format, AUDIO_DEVICE_FORMAT, channels, AUDIO_DEVICE_CHANNELS, sampleRate, AUDIO.System.device.sampleRate);
551 converterConfig.resampling.allowDynamicSampleRate = true; // Required for pitch shifting
553 ma_result result = ma_data_converter_init(&converterConfig, &audioBuffer->converter);
555 if (result != MA_SUCCESS)
557 TRACELOG(LOG_WARNING, "AUDIO: Failed to create data conversion pipeline");
558 RL_FREE(audioBuffer);
562 // Init audio buffer values
563 audioBuffer->volume = 1.0f;
564 audioBuffer->pitch = 1.0f;
565 audioBuffer->playing = false;
566 audioBuffer->paused = false;
567 audioBuffer->looping = false;
568 audioBuffer->usage = usage;
569 audioBuffer->frameCursorPos = 0;
570 audioBuffer->sizeInFrames = sizeInFrames;
572 // Buffers should be marked as processed by default so that a call to
573 // UpdateAudioStream() immediately after initialization works correctly
574 audioBuffer->isSubBufferProcessed[0] = true;
575 audioBuffer->isSubBufferProcessed[1] = true;
577 // Track audio buffer to linked list next position
578 TrackAudioBuffer(audioBuffer);
583 // Delete an audio buffer
584 void UnloadAudioBuffer(AudioBuffer *buffer)
588 ma_data_converter_uninit(&buffer->converter);
589 UntrackAudioBuffer(buffer);
590 RL_FREE(buffer->data);
595 // Check if an audio buffer is playing
596 bool IsAudioBufferPlaying(AudioBuffer *buffer)
600 if (buffer != NULL) result = (buffer->playing && !buffer->paused);
605 // Play an audio buffer
606 // NOTE: Buffer is restarted to the start.
607 // Use PauseAudioBuffer() and ResumeAudioBuffer() if the playback position should be maintained.
608 void PlayAudioBuffer(AudioBuffer *buffer)
612 buffer->playing = true;
613 buffer->paused = false;
614 buffer->frameCursorPos = 0;
618 // Stop an audio buffer
619 void StopAudioBuffer(AudioBuffer *buffer)
623 if (IsAudioBufferPlaying(buffer))
625 buffer->playing = false;
626 buffer->paused = false;
627 buffer->frameCursorPos = 0;
628 buffer->totalFramesProcessed = 0;
629 buffer->isSubBufferProcessed[0] = true;
630 buffer->isSubBufferProcessed[1] = true;
635 // Pause an audio buffer
636 void PauseAudioBuffer(AudioBuffer *buffer)
638 if (buffer != NULL) buffer->paused = true;
641 // Resume an audio buffer
642 void ResumeAudioBuffer(AudioBuffer *buffer)
644 if (buffer != NULL) buffer->paused = false;
647 // Set volume for an audio buffer
648 void SetAudioBufferVolume(AudioBuffer *buffer, float volume)
650 if (buffer != NULL) buffer->volume = volume;
653 // Set pitch for an audio buffer
654 void SetAudioBufferPitch(AudioBuffer *buffer, float pitch)
656 if ((buffer != NULL) && (pitch > 0.0f))
658 // Pitching is just an adjustment of the sample rate.
659 // Note that this changes the duration of the sound:
660 // - higher pitches will make the sound faster
661 // - lower pitches make it slower
662 ma_uint32 outputSampleRate = (ma_uint32)((float)buffer->converter.config.sampleRateOut/pitch);
663 ma_data_converter_set_rate(&buffer->converter, buffer->converter.config.sampleRateIn, outputSampleRate);
665 buffer->pitch = pitch;
669 // Track audio buffer to linked list next position
670 void TrackAudioBuffer(AudioBuffer *buffer)
672 ma_mutex_lock(&AUDIO.System.lock);
674 if (AUDIO.Buffer.first == NULL) AUDIO.Buffer.first = buffer;
677 AUDIO.Buffer.last->next = buffer;
678 buffer->prev = AUDIO.Buffer.last;
681 AUDIO.Buffer.last = buffer;
683 ma_mutex_unlock(&AUDIO.System.lock);
686 // Untrack audio buffer from linked list
687 void UntrackAudioBuffer(AudioBuffer *buffer)
689 ma_mutex_lock(&AUDIO.System.lock);
691 if (buffer->prev == NULL) AUDIO.Buffer.first = buffer->next;
692 else buffer->prev->next = buffer->next;
694 if (buffer->next == NULL) AUDIO.Buffer.last = buffer->prev;
695 else buffer->next->prev = buffer->prev;
700 ma_mutex_unlock(&AUDIO.System.lock);
703 //----------------------------------------------------------------------------------
704 // Module Functions Definition - Sounds loading and playing (.WAV)
705 //----------------------------------------------------------------------------------
707 // Load wave data from file
708 Wave LoadWave(const char *fileName)
712 // Loading file to memory
713 unsigned int fileSize = 0;
714 unsigned char *fileData = LoadFileData(fileName, &fileSize);
716 if (fileData != NULL)
718 // Loading wave from memory data
719 wave = LoadWaveFromMemory(GetFileExtension(fileName), fileData, fileSize);
727 // Load wave from memory buffer, fileType refers to extension: i.e. ".wav"
728 Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize)
732 char fileExtLower[16] = { 0 };
733 strcpy(fileExtLower, TextToLower(fileType));
736 #if defined(SUPPORT_FILEFORMAT_WAV)
737 else if (TextIsEqual(fileExtLower, ".wav")) wave = LoadWAV(fileData, dataSize);
739 #if defined(SUPPORT_FILEFORMAT_OGG)
740 else if (TextIsEqual(fileExtLower, ".ogg")) wave = LoadOGG(fileData, dataSize);
742 #if defined(SUPPORT_FILEFORMAT_FLAC)
743 else if (TextIsEqual(fileExtLower, ".flac")) wave = LoadFLAC(fileData, dataSize);
745 #if defined(SUPPORT_FILEFORMAT_MP3)
746 else if (TextIsEqual(fileExtLower, ".mp3")) wave = LoadMP3(fileData, dataSize);
748 else TRACELOG(LOG_WARNING, "WAVE: File format not supported");
753 // Load sound from file
754 // NOTE: The entire file is loaded to memory to be played (no-streaming)
755 Sound LoadSound(const char *fileName)
757 Wave wave = LoadWave(fileName);
759 Sound sound = LoadSoundFromWave(wave);
761 UnloadWave(wave); // Sound is loaded, we can unload wave
766 // Load sound from wave data
767 // NOTE: Wave data must be unallocated manually
768 Sound LoadSoundFromWave(Wave wave)
772 if (wave.data != NULL)
774 // When using miniaudio we need to do our own mixing.
775 // To simplify this we need convert the format of each sound to be consistent with
776 // the format used to open the playback AUDIO.System.device. We can do this two ways:
778 // 1) Convert the whole sound in one go at load time (here).
779 // 2) Convert the audio data in chunks at mixing time.
781 // First option has been selected, format conversion is done on the loading stage.
782 // The downside is that it uses more memory if the original sound is u8 or s16.
783 ma_format formatIn = ((wave.sampleSize == 8)? ma_format_u8 : ((wave.sampleSize == 16)? ma_format_s16 : ma_format_f32));
784 ma_uint32 frameCountIn = wave.sampleCount/wave.channels;
786 ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, NULL, frameCountIn, formatIn, wave.channels, wave.sampleRate);
787 if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed to get frame count for format conversion");
789 AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, frameCount, AUDIO_BUFFER_USAGE_STATIC);
790 if (audioBuffer == NULL)
792 TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer");
793 return sound; // early return to avoid dereferencing the audioBuffer null pointer
796 frameCount = (ma_uint32)ma_convert_frames(audioBuffer->data, frameCount, AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, wave.data, frameCountIn, formatIn, wave.channels, wave.sampleRate);
797 if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed format conversion");
799 sound.sampleCount = frameCount*AUDIO_DEVICE_CHANNELS;
800 sound.stream.sampleRate = AUDIO.System.device.sampleRate;
801 sound.stream.sampleSize = 32;
802 sound.stream.channels = AUDIO_DEVICE_CHANNELS;
803 sound.stream.buffer = audioBuffer;
810 void UnloadWave(Wave wave)
812 if (wave.data != NULL) RL_FREE(wave.data);
814 TRACELOG(LOG_INFO, "WAVE: Unloaded wave data from RAM");
818 void UnloadSound(Sound sound)
820 UnloadAudioBuffer(sound.stream.buffer);
822 TRACELOG(LOG_INFO, "WAVE: Unloaded sound data from RAM");
825 // Update sound buffer with new data
826 void UpdateSound(Sound sound, const void *data, int samplesCount)
828 if (sound.stream.buffer != NULL)
830 StopAudioBuffer(sound.stream.buffer);
832 // TODO: May want to lock/unlock this since this data buffer is read at mixing time
833 memcpy(sound.stream.buffer->data, data, samplesCount*ma_get_bytes_per_frame(sound.stream.buffer->converter.config.formatIn, sound.stream.buffer->converter.config.channelsIn));
837 // Export wave data to file
838 bool ExportWave(Wave wave, const char *fileName)
840 bool success = false;
843 #if defined(SUPPORT_FILEFORMAT_WAV)
844 else if (IsFileExtension(fileName, ".wav")) success = SaveWAV(wave, fileName);
846 else if (IsFileExtension(fileName, ".raw"))
848 // Export raw sample data (without header)
849 // NOTE: It's up to the user to track wave parameters
850 success = SaveFileData(fileName, wave.data, wave.sampleCount*wave.sampleSize/8);
853 if (success) TRACELOG(LOG_INFO, "FILEIO: [%s] Wave data exported successfully", fileName);
854 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export wave data", fileName);
859 // Export wave sample data to code (.h)
860 bool ExportWaveAsCode(Wave wave, const char *fileName)
862 bool success = false;
864 #ifndef TEXT_BYTES_PER_LINE
865 #define TEXT_BYTES_PER_LINE 20
868 int waveDataSize = wave.sampleCount*wave.channels*wave.sampleSize/8;
870 // NOTE: Text data buffer size is estimated considering wave data size in bytes
871 // and requiring 6 char bytes for every byte: "0x00, "
872 char *txtData = (char *)RL_CALLOC(6*waveDataSize + 2000, sizeof(char));
875 bytesCount += sprintf(txtData + bytesCount, "\n//////////////////////////////////////////////////////////////////////////////////\n");
876 bytesCount += sprintf(txtData + bytesCount, "// //\n");
877 bytesCount += sprintf(txtData + bytesCount, "// WaveAsCode exporter v1.0 - Wave data exported as an array of bytes //\n");
878 bytesCount += sprintf(txtData + bytesCount, "// //\n");
879 bytesCount += sprintf(txtData + bytesCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
880 bytesCount += sprintf(txtData + bytesCount, "// feedback and support: ray[at]raylib.com //\n");
881 bytesCount += sprintf(txtData + bytesCount, "// //\n");
882 bytesCount += sprintf(txtData + bytesCount, "// Copyright (c) 2018 Ramon Santamaria (@raysan5) //\n");
883 bytesCount += sprintf(txtData + bytesCount, "// //\n");
884 bytesCount += sprintf(txtData + bytesCount, "//////////////////////////////////////////////////////////////////////////////////\n\n");
886 char varFileName[256] = { 0 };
887 #if !defined(RAUDIO_STANDALONE)
888 // Get file name from path and convert variable name to uppercase
889 strcpy(varFileName, GetFileNameWithoutExt(fileName));
890 for (int i = 0; varFileName[i] != '\0'; i++) if (varFileName[i] >= 'a' && varFileName[i] <= 'z') { varFileName[i] = varFileName[i] - 32; }
892 strcpy(varFileName, fileName);
895 bytesCount += sprintf(txtData + bytesCount, "// Wave data information\n");
896 bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_COUNT %u\n", varFileName, wave.sampleCount);
897 bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_RATE %u\n", varFileName, wave.sampleRate);
898 bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_SIZE %u\n", varFileName, wave.sampleSize);
899 bytesCount += sprintf(txtData + bytesCount, "#define %s_CHANNELS %u\n\n", varFileName, wave.channels);
901 // Write byte data as hexadecimal text
902 bytesCount += sprintf(txtData + bytesCount, "static unsigned char %s_DATA[%i] = { ", varFileName, waveDataSize);
903 for (int i = 0; i < waveDataSize - 1; i++) bytesCount += sprintf(txtData + bytesCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), ((unsigned char *)wave.data)[i]);
904 bytesCount += sprintf(txtData + bytesCount, "0x%x };\n", ((unsigned char *)wave.data)[waveDataSize - 1]);
906 // NOTE: Text data length exported is determined by '\0' (NULL) character
907 success = SaveFileText(fileName, txtData);
915 void PlaySound(Sound sound)
917 PlayAudioBuffer(sound.stream.buffer);
920 // Play a sound in the multichannel buffer pool
921 void PlaySoundMulti(Sound sound)
924 unsigned int oldAge = 0;
927 // find the first non playing pool entry
928 for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
930 if (AUDIO.MultiChannel.channels[i] > oldAge)
932 oldAge = AUDIO.MultiChannel.channels[i];
936 if (!IsAudioBufferPlaying(AUDIO.MultiChannel.pool[i]))
943 // If no none playing pool members can be index choose the oldest
946 TRACELOG(LOG_WARNING, "SOUND: Buffer pool is already full, count: %i", AUDIO.MultiChannel.poolCounter);
950 // Shouldn't be able to get here... but just in case something odd happens!
951 TRACELOG(LOG_WARNING, "SOUND: Buffer pool could not determine oldest buffer not playing sound");
958 StopAudioBuffer(AUDIO.MultiChannel.pool[index]);
961 // Experimentally mutex lock doesn't seem to be needed this makes sense
962 // as pool[index] isn't playing and the only stuff we're copying
963 // shouldn't be changing...
965 AUDIO.MultiChannel.channels[index] = AUDIO.MultiChannel.poolCounter;
966 AUDIO.MultiChannel.poolCounter++;
968 AUDIO.MultiChannel.pool[index]->volume = sound.stream.buffer->volume;
969 AUDIO.MultiChannel.pool[index]->pitch = sound.stream.buffer->pitch;
970 AUDIO.MultiChannel.pool[index]->looping = sound.stream.buffer->looping;
971 AUDIO.MultiChannel.pool[index]->usage = sound.stream.buffer->usage;
972 AUDIO.MultiChannel.pool[index]->isSubBufferProcessed[0] = false;
973 AUDIO.MultiChannel.pool[index]->isSubBufferProcessed[1] = false;
974 AUDIO.MultiChannel.pool[index]->sizeInFrames = sound.stream.buffer->sizeInFrames;
975 AUDIO.MultiChannel.pool[index]->data = sound.stream.buffer->data;
977 PlayAudioBuffer(AUDIO.MultiChannel.pool[index]);
980 // Stop any sound played with PlaySoundMulti()
981 void StopSoundMulti(void)
983 for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++) StopAudioBuffer(AUDIO.MultiChannel.pool[i]);
986 // Get number of sounds playing in the multichannel buffer pool
987 int GetSoundsPlaying(void)
991 for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
993 if (IsAudioBufferPlaying(AUDIO.MultiChannel.pool[i])) counter++;
1000 void PauseSound(Sound sound)
1002 PauseAudioBuffer(sound.stream.buffer);
1005 // Resume a paused sound
1006 void ResumeSound(Sound sound)
1008 ResumeAudioBuffer(sound.stream.buffer);
1011 // Stop reproducing a sound
1012 void StopSound(Sound sound)
1014 StopAudioBuffer(sound.stream.buffer);
1017 // Check if a sound is playing
1018 bool IsSoundPlaying(Sound sound)
1020 return IsAudioBufferPlaying(sound.stream.buffer);
1023 // Set volume for a sound
1024 void SetSoundVolume(Sound sound, float volume)
1026 SetAudioBufferVolume(sound.stream.buffer, volume);
1029 // Set pitch for a sound
1030 void SetSoundPitch(Sound sound, float pitch)
1032 SetAudioBufferPitch(sound.stream.buffer, pitch);
1035 // Convert wave data to desired format
1036 void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
1038 ma_format formatIn = ((wave->sampleSize == 8)? ma_format_u8 : ((wave->sampleSize == 16)? ma_format_s16 : ma_format_f32));
1039 ma_format formatOut = ((sampleSize == 8)? ma_format_u8 : ((sampleSize == 16)? ma_format_s16 : ma_format_f32));
1041 ma_uint32 frameCountIn = wave->sampleCount/wave->channels;
1043 ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, formatOut, channels, sampleRate, NULL, frameCountIn, formatIn, wave->channels, wave->sampleRate);
1044 if (frameCount == 0)
1046 TRACELOG(LOG_WARNING, "WAVE: Failed to get frame count for format conversion");
1050 void *data = RL_MALLOC(frameCount*channels*(sampleSize/8));
1052 frameCount = (ma_uint32)ma_convert_frames(data, frameCount, formatOut, channels, sampleRate, wave->data, frameCountIn, formatIn, wave->channels, wave->sampleRate);
1053 if (frameCount == 0)
1055 TRACELOG(LOG_WARNING, "WAVE: Failed format conversion");
1059 wave->sampleCount = frameCount*channels;
1060 wave->sampleSize = sampleSize;
1061 wave->sampleRate = sampleRate;
1062 wave->channels = channels;
1063 RL_FREE(wave->data);
1067 // Copy a wave to a new wave
1068 Wave WaveCopy(Wave wave)
1070 Wave newWave = { 0 };
1072 newWave.data = RL_MALLOC(wave.sampleCount*wave.sampleSize/8);
1074 if (newWave.data != NULL)
1076 // NOTE: Size must be provided in bytes
1077 memcpy(newWave.data, wave.data, wave.sampleCount*wave.sampleSize/8);
1079 newWave.sampleCount = wave.sampleCount;
1080 newWave.sampleRate = wave.sampleRate;
1081 newWave.sampleSize = wave.sampleSize;
1082 newWave.channels = wave.channels;
1088 // Crop a wave to defined samples range
1089 // NOTE: Security check in case of out-of-range
1090 void WaveCrop(Wave *wave, int initSample, int finalSample)
1092 if ((initSample >= 0) && (initSample < finalSample) &&
1093 (finalSample > 0) && ((unsigned int)finalSample < wave->sampleCount))
1095 int sampleCount = finalSample - initSample;
1097 void *data = RL_MALLOC(sampleCount*wave->sampleSize/8);
1099 memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->sampleSize/8);
1101 RL_FREE(wave->data);
1104 else TRACELOG(LOG_WARNING, "WAVE: Crop range out of bounds");
1107 // Load samples data from wave as a floats array
1108 // NOTE 1: Returned sample values are normalized to range [-1..1]
1109 // NOTE 2: Sample data allocated should be freed with UnloadWaveSamples()
1110 float *LoadWaveSamples(Wave wave)
1112 float *samples = (float *)RL_MALLOC(wave.sampleCount*sizeof(float));
1114 // NOTE: sampleCount is the total number of interlaced samples (including channels)
1116 for (unsigned int i = 0; i < wave.sampleCount; i++)
1118 if (wave.sampleSize == 8) samples[i] = (float)(((unsigned char *)wave.data)[i] - 127)/256.0f;
1119 else if (wave.sampleSize == 16) samples[i] = (float)(((short *)wave.data)[i])/32767.0f;
1120 else if (wave.sampleSize == 32) samples[i] = ((float *)wave.data)[i];
1126 // Unload samples data loaded with LoadWaveSamples()
1127 void UnloadWaveSamples(float *samples)
1132 //----------------------------------------------------------------------------------
1133 // Module Functions Definition - Music loading and stream playing (.OGG)
1134 //----------------------------------------------------------------------------------
1136 // Load music stream from file
1137 Music LoadMusicStream(const char *fileName)
1139 Music music = { 0 };
1140 bool musicLoaded = false;
1143 #if defined(SUPPORT_FILEFORMAT_WAV)
1144 else if (IsFileExtension(fileName, ".wav"))
1146 drwav *ctxWav = RL_CALLOC(1, sizeof(drwav));
1147 bool success = drwav_init_file(ctxWav, fileName, NULL);
1149 music.ctxType = MUSIC_AUDIO_WAV;
1150 music.ctxData = ctxWav;
1154 int sampleSize = ctxWav->bitsPerSample;
1155 if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
1157 music.stream = InitAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
1158 music.sampleCount = (unsigned int)ctxWav->totalPCMFrameCount*ctxWav->channels;
1159 music.looping = true; // Looping enabled by default
1164 #if defined(SUPPORT_FILEFORMAT_OGG)
1165 else if (IsFileExtension(fileName, ".ogg"))
1167 // Open ogg audio stream
1168 music.ctxType = MUSIC_AUDIO_OGG;
1169 music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL);
1171 if (music.ctxData != NULL)
1173 stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info
1175 // OGG bit rate defaults to 16 bit, it's enough for compressed format
1176 music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
1178 // WARNING: It seems this function returns length in frames, not samples, so we multiply by channels
1179 music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
1180 music.looping = true; // Looping enabled by default
1185 #if defined(SUPPORT_FILEFORMAT_FLAC)
1186 else if (IsFileExtension(fileName, ".flac"))
1188 music.ctxType = MUSIC_AUDIO_FLAC;
1189 music.ctxData = drflac_open_file(fileName, NULL);
1191 if (music.ctxData != NULL)
1193 drflac *ctxFlac = (drflac *)music.ctxData;
1195 music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
1196 music.sampleCount = (unsigned int)ctxFlac->totalPCMFrameCount*ctxFlac->channels;
1197 music.looping = true; // Looping enabled by default
1202 #if defined(SUPPORT_FILEFORMAT_MP3)
1203 else if (IsFileExtension(fileName, ".mp3"))
1205 drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3));
1206 int result = drmp3_init_file(ctxMp3, fileName, NULL);
1208 music.ctxType = MUSIC_AUDIO_MP3;
1209 music.ctxData = ctxMp3;
1213 music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
1214 music.sampleCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
1215 music.looping = true; // Looping enabled by default
1220 #if defined(SUPPORT_FILEFORMAT_XM)
1221 else if (IsFileExtension(fileName, ".xm"))
1223 jar_xm_context_t *ctxXm = NULL;
1224 int result = jar_xm_create_context_from_file(&ctxXm, AUDIO.System.device.sampleRate, fileName);
1226 music.ctxType = MUSIC_MODULE_XM;
1227 music.ctxData = ctxXm;
1229 if (result == 0) // XM AUDIO.System.context created successfully
1231 jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
1233 unsigned int bits = 32;
1234 if (AUDIO_DEVICE_FORMAT == ma_format_s16)
1236 else if (AUDIO_DEVICE_FORMAT == ma_format_u8)
1239 // NOTE: Only stereo is supported for XM
1240 music.stream = InitAudioStream(AUDIO.System.device.sampleRate, bits, AUDIO_DEVICE_CHANNELS);
1241 music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2; // 2 channels
1242 music.looping = true; // Looping enabled by default
1243 jar_xm_reset(ctxXm); // make sure we start at the beginning of the song
1248 #if defined(SUPPORT_FILEFORMAT_MOD)
1249 else if (IsFileExtension(fileName, ".mod"))
1251 jar_mod_context_t *ctxMod = RL_CALLOC(1, sizeof(jar_mod_context_t));
1252 jar_mod_init(ctxMod);
1253 int result = jar_mod_load_file(ctxMod, fileName);
1255 music.ctxType = MUSIC_MODULE_MOD;
1256 music.ctxData = ctxMod;
1260 // NOTE: Only stereo is supported for MOD
1261 music.stream = InitAudioStream(AUDIO.System.device.sampleRate, 16, AUDIO_DEVICE_CHANNELS);
1262 music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2; // 2 channels
1263 music.looping = true; // Looping enabled by default
1268 else TRACELOG(LOG_WARNING, "STREAM: [%s] Fileformat not supported", fileName);
1273 #if defined(SUPPORT_FILEFORMAT_WAV)
1274 else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1276 #if defined(SUPPORT_FILEFORMAT_OGG)
1277 else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1279 #if defined(SUPPORT_FILEFORMAT_FLAC)
1280 else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
1282 #if defined(SUPPORT_FILEFORMAT_MP3)
1283 else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1285 #if defined(SUPPORT_FILEFORMAT_XM)
1286 else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1288 #if defined(SUPPORT_FILEFORMAT_MOD)
1289 else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1292 music.ctxData = NULL;
1293 TRACELOG(LOG_WARNING, "FILEIO: [%s] Music file could not be opened", fileName);
1297 // Show some music stream info
1298 TRACELOG(LOG_INFO, "FILEIO: [%s] Music file successfully loaded:", fileName);
1299 TRACELOG(LOG_INFO, " > Total samples: %i", music.sampleCount);
1300 TRACELOG(LOG_INFO, " > Sample rate: %i Hz", music.stream.sampleRate);
1301 TRACELOG(LOG_INFO, " > Sample size: %i bits", music.stream.sampleSize);
1302 TRACELOG(LOG_INFO, " > Channels: %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
1308 // extension including period ".mod"
1309 Music LoadMusicStreamFromMemory(const char *fileType, unsigned char* data, int dataSize)
1311 Music music = { 0 };
1312 bool musicLoaded = false;
1314 char fileExtLower[16] = { 0 };
1315 strcpy(fileExtLower, TextToLower(fileType));
1318 #if defined(SUPPORT_FILEFORMAT_WAV)
1319 else if (TextIsEqual(fileExtLower, ".wav"))
1321 drwav *ctxWav = RL_CALLOC(1, sizeof(drwav));
1323 bool success = drwav_init_memory(ctxWav, (const void*)data, dataSize, NULL);
1325 music.ctxType = MUSIC_AUDIO_WAV;
1326 music.ctxData = ctxWav;
1330 int sampleSize = ctxWav->bitsPerSample;
1331 if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
1333 music.stream = InitAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
1334 music.sampleCount = (unsigned int)ctxWav->totalPCMFrameCount*ctxWav->channels;
1335 music.looping = true; // Looping enabled by default
1340 #if defined(SUPPORT_FILEFORMAT_FLAC)
1341 else if (TextIsEqual(fileExtLower, ".flac"))
1343 music.ctxType = MUSIC_AUDIO_FLAC;
1344 music.ctxData = drflac_open_memory((const void*)data, dataSize, NULL);
1346 if (music.ctxData != NULL)
1348 drflac *ctxFlac = (drflac *)music.ctxData;
1350 music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
1351 music.sampleCount = (unsigned int)ctxFlac->totalPCMFrameCount*ctxFlac->channels;
1352 music.looping = true; // Looping enabled by default
1357 #if defined(SUPPORT_FILEFORMAT_MP3)
1358 else if (TextIsEqual(fileExtLower, ".mp3"))
1360 drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3));
1361 int success = drmp3_init_memory(ctxMp3, (const void*)data, dataSize, NULL);
1363 music.ctxType = MUSIC_AUDIO_MP3;
1364 music.ctxData = ctxMp3;
1368 music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
1369 music.sampleCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
1370 music.looping = true; // Looping enabled by default
1375 #if defined(SUPPORT_FILEFORMAT_OGG)
1376 else if (TextIsEqual(fileExtLower, ".ogg"))
1378 // Open ogg audio stream
1379 music.ctxType = MUSIC_AUDIO_OGG;
1380 //music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL);
1381 music.ctxData = stb_vorbis_open_memory((const unsigned char*)data, dataSize, NULL, NULL);
1383 if (music.ctxData != NULL)
1385 stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info
1387 // OGG bit rate defaults to 16 bit, it's enough for compressed format
1388 music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
1390 // WARNING: It seems this function returns length in frames, not samples, so we multiply by channels
1391 music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
1392 music.looping = true; // Looping enabled by default
1397 #if defined(SUPPORT_FILEFORMAT_XM)
1398 else if (TextIsEqual(fileExtLower, ".xm"))
1400 jar_xm_context_t *ctxXm = NULL;
1401 int result = jar_xm_create_context_safe(&ctxXm, (const char*)data, dataSize, AUDIO.System.device.sampleRate);
1402 if (result == 0) // XM AUDIO.System.context created successfully
1404 music.ctxType = MUSIC_MODULE_XM;
1405 jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
1407 unsigned int bits = 32;
1408 if (AUDIO_DEVICE_FORMAT == ma_format_s16)
1410 else if (AUDIO_DEVICE_FORMAT == ma_format_u8)
1413 // NOTE: Only stereo is supported for XM
1414 music.stream = InitAudioStream(AUDIO.System.device.sampleRate, bits, 2);
1415 music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2; // 2 channels
1416 music.looping = true; // Looping enabled by default
1417 jar_xm_reset(ctxXm); // make sure we start at the beginning of the song
1419 music.ctxData = ctxXm;
1424 #if defined(SUPPORT_FILEFORMAT_MOD)
1425 else if (TextIsEqual(fileExtLower, ".mod"))
1427 jar_mod_context_t *ctxMod = RL_MALLOC(sizeof(jar_mod_context_t));
1430 jar_mod_init(ctxMod);
1432 // copy data to allocated memory for default UnloadMusicStream
1433 unsigned char *newData = RL_MALLOC(dataSize);
1434 int it = dataSize/sizeof(unsigned char);
1435 for (int i = 0; i < it; i++){
1436 newData[i] = data[i];
1439 // Memory loaded version for jar_mod_load_file()
1440 if (dataSize && dataSize < 32*1024*1024)
1442 ctxMod->modfilesize = dataSize;
1443 ctxMod->modfile = newData;
1444 if (jar_mod_load(ctxMod, (void *)ctxMod->modfile, dataSize)) result = dataSize;
1449 music.ctxType = MUSIC_MODULE_MOD;
1451 // NOTE: Only stereo is supported for MOD
1452 music.stream = InitAudioStream(AUDIO.System.device.sampleRate, 16, 2);
1453 music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2; // 2 channels
1454 music.looping = true; // Looping enabled by default
1457 music.ctxData = ctxMod;
1462 else TRACELOG(LOG_WARNING, "STREAM: [%s] Fileformat not supported", fileType);
1467 #if defined(SUPPORT_FILEFORMAT_WAV)
1468 else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1470 #if defined(SUPPORT_FILEFORMAT_FLAC)
1471 else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
1473 #if defined(SUPPORT_FILEFORMAT_MP3)
1474 else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1476 #if defined(SUPPORT_FILEFORMAT_OGG)
1477 else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1479 #if defined(SUPPORT_FILEFORMAT_XM)
1480 else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1482 #if defined(SUPPORT_FILEFORMAT_MOD)
1483 else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1486 music.ctxData = NULL;
1487 TRACELOG(LOG_WARNING, "FILEIO: [%s] Music memory could not be opened", fileType);
1491 // Show some music stream info
1492 TRACELOG(LOG_INFO, "FILEIO: [%s] Music memory successfully loaded:", fileType);
1493 TRACELOG(LOG_INFO, " > Total samples: %i", music.sampleCount);
1494 TRACELOG(LOG_INFO, " > Sample rate: %i Hz", music.stream.sampleRate);
1495 TRACELOG(LOG_INFO, " > Sample size: %i bits", music.stream.sampleSize);
1496 TRACELOG(LOG_INFO, " > Channels: %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
1502 // Unload music stream
1503 void UnloadMusicStream(Music music)
1505 CloseAudioStream(music.stream);
1507 if (music.ctxData != NULL)
1510 #if defined(SUPPORT_FILEFORMAT_WAV)
1511 else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1513 #if defined(SUPPORT_FILEFORMAT_OGG)
1514 else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1516 #if defined(SUPPORT_FILEFORMAT_FLAC)
1517 else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
1519 #if defined(SUPPORT_FILEFORMAT_MP3)
1520 else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1522 #if defined(SUPPORT_FILEFORMAT_XM)
1523 else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1525 #if defined(SUPPORT_FILEFORMAT_MOD)
1526 else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1531 // Start music playing (open stream)
1532 void PlayMusicStream(Music music)
1534 if (music.stream.buffer != NULL)
1536 // For music streams, we need to make sure we maintain the frame cursor position
1537 // This is a hack for this section of code in UpdateMusicStream()
1538 // NOTE: In case window is minimized, music stream is stopped, just make sure to
1539 // play again on window restore: if (IsMusicPlaying(music)) PlayMusicStream(music);
1540 ma_uint32 frameCursorPos = music.stream.buffer->frameCursorPos;
1541 PlayAudioStream(music.stream); // WARNING: This resets the cursor position.
1542 music.stream.buffer->frameCursorPos = frameCursorPos;
1546 // Pause music playing
1547 void PauseMusicStream(Music music)
1549 PauseAudioStream(music.stream);
1552 // Resume music playing
1553 void ResumeMusicStream(Music music)
1555 ResumeAudioStream(music.stream);
1558 // Stop music playing (close stream)
1559 void StopMusicStream(Music music)
1561 StopAudioStream(music.stream);
1563 switch (music.ctxType)
1565 #if defined(SUPPORT_FILEFORMAT_WAV)
1566 case MUSIC_AUDIO_WAV: drwav_seek_to_pcm_frame((drwav *)music.ctxData, 0); break;
1568 #if defined(SUPPORT_FILEFORMAT_OGG)
1569 case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break;
1571 #if defined(SUPPORT_FILEFORMAT_FLAC)
1572 case MUSIC_AUDIO_FLAC: drflac_seek_to_pcm_frame((drflac *)music.ctxData, 0); break;
1574 #if defined(SUPPORT_FILEFORMAT_MP3)
1575 case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame((drmp3 *)music.ctxData, 0); break;
1577 #if defined(SUPPORT_FILEFORMAT_XM)
1578 case MUSIC_MODULE_XM: jar_xm_reset((jar_xm_context_t *)music.ctxData); break;
1580 #if defined(SUPPORT_FILEFORMAT_MOD)
1581 case MUSIC_MODULE_MOD: jar_mod_seek_start((jar_mod_context_t *)music.ctxData); break;
1587 // Update (re-fill) music buffers if data already processed
1588 void UpdateMusicStream(Music music)
1590 if (music.stream.buffer == NULL)
1593 if (music.ctxType == MUSIC_MODULE_XM)
1594 jar_xm_set_max_loop_count(music.ctxData, music.looping ? 0 : 1);
1596 bool streamEnding = false;
1598 unsigned int subBufferSizeInFrames = music.stream.buffer->sizeInFrames/2;
1600 // NOTE: Using dynamic allocation because it could require more than 16KB
1601 void *pcm = RL_CALLOC(subBufferSizeInFrames*music.stream.channels*music.stream.sampleSize/8, 1);
1603 int samplesCount = 0; // Total size of data streamed in L+R samples for xm floats, individual L or R for ogg shorts
1605 // TODO: Get the sampleLeft using totalFramesProcessed... but first, get total frames processed correctly...
1606 //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
1607 int sampleLeft = music.sampleCount - (music.stream.buffer->totalFramesProcessed*music.stream.channels);
1609 if (music.ctxType == MUSIC_MODULE_XM && music.looping) sampleLeft = subBufferSizeInFrames*4;
1611 while (IsAudioStreamProcessed(music.stream))
1613 if ((sampleLeft/music.stream.channels) >= subBufferSizeInFrames) samplesCount = subBufferSizeInFrames*music.stream.channels;
1614 else samplesCount = sampleLeft;
1616 switch (music.ctxType)
1618 #if defined(SUPPORT_FILEFORMAT_WAV)
1619 case MUSIC_AUDIO_WAV:
1621 // NOTE: Returns the number of samples to process (not required)
1622 if (music.stream.sampleSize == 16) drwav_read_pcm_frames_s16((drwav *)music.ctxData, samplesCount/music.stream.channels, (short *)pcm);
1623 else if (music.stream.sampleSize == 32) drwav_read_pcm_frames_f32((drwav *)music.ctxData, samplesCount/music.stream.channels, (float *)pcm);
1627 #if defined(SUPPORT_FILEFORMAT_OGG)
1628 case MUSIC_AUDIO_OGG:
1630 // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
1631 stb_vorbis_get_samples_short_interleaved((stb_vorbis *)music.ctxData, music.stream.channels, (short *)pcm, samplesCount);
1635 #if defined(SUPPORT_FILEFORMAT_FLAC)
1636 case MUSIC_AUDIO_FLAC:
1638 // NOTE: Returns the number of samples to process (not required)
1639 drflac_read_pcm_frames_s16((drflac *)music.ctxData, samplesCount, (short *)pcm);
1643 #if defined(SUPPORT_FILEFORMAT_MP3)
1644 case MUSIC_AUDIO_MP3:
1646 // NOTE: samplesCount, actually refers to framesCount and returns the number of frames processed
1647 drmp3_read_pcm_frames_f32((drmp3 *)music.ctxData, samplesCount/music.stream.channels, (float *)pcm);
1651 #if defined(SUPPORT_FILEFORMAT_XM)
1652 case MUSIC_MODULE_XM:
1654 switch (AUDIO_DEVICE_FORMAT)
1657 // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
1658 jar_xm_generate_samples((jar_xm_context_t*)music.ctxData, (float*)pcm, samplesCount / 2);
1662 // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
1663 jar_xm_generate_samples_16bit((jar_xm_context_t*)music.ctxData, (short*)pcm, samplesCount / 2);
1667 // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
1668 jar_xm_generate_samples_8bit((jar_xm_context_t*)music.ctxData, (char*)pcm, samplesCount / 2);
1674 #if defined(SUPPORT_FILEFORMAT_MOD)
1675 case MUSIC_MODULE_MOD:
1677 // NOTE: 3rd parameter (nbsample) specify the number of stereo 16bits samples you want, so sampleCount/2
1678 jar_mod_fillbuffer((jar_mod_context_t *)music.ctxData, (short *)pcm, samplesCount/2, 0);
1684 UpdateAudioStream(music.stream, pcm, samplesCount);
1686 if ((music.ctxType == MUSIC_MODULE_XM) || music.ctxType == MUSIC_MODULE_MOD)
1688 if (samplesCount > 1) sampleLeft -= samplesCount/2;
1689 else sampleLeft -= samplesCount;
1691 else sampleLeft -= samplesCount;
1693 if (sampleLeft <= 0)
1695 streamEnding = true;
1700 // Free allocated pcm data
1703 // Reset audio stream for looping
1706 StopMusicStream(music); // Stop music (and reset)
1707 if (music.looping) PlayMusicStream(music); // Play again
1711 // NOTE: In case window is minimized, music stream is stopped,
1712 // just make sure to play again on window restore
1713 if (IsMusicPlaying(music)) PlayMusicStream(music);
1717 // Check if any music is playing
1718 bool IsMusicPlaying(Music music)
1720 return IsAudioStreamPlaying(music.stream);
1723 // Set volume for music
1724 void SetMusicVolume(Music music, float volume)
1726 SetAudioStreamVolume(music.stream, volume);
1729 // Set pitch for music
1730 void SetMusicPitch(Music music, float pitch)
1732 SetAudioBufferPitch(music.stream.buffer, pitch);
1735 // Get music time length (in seconds)
1736 float GetMusicTimeLength(Music music)
1738 float totalSeconds = 0.0f;
1740 totalSeconds = (float)music.sampleCount/(music.stream.sampleRate*music.stream.channels);
1742 return totalSeconds;
1745 // Get current music time played (in seconds)
1746 float GetMusicTimePlayed(Music music)
1748 #if defined(SUPPORT_FILEFORMAT_XM)
1749 if (music.ctxType == MUSIC_MODULE_XM)
1751 uint64_t samples = 0;
1752 jar_xm_get_position(music.ctxData, NULL, NULL, NULL, &samples);
1753 samples = samples % (music.sampleCount);
1755 return (float)(samples)/(music.stream.sampleRate*music.stream.channels);
1758 float secondsPlayed = 0.0f;
1759 if (music.stream.buffer != NULL)
1761 //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
1762 unsigned int samplesPlayed = music.stream.buffer->totalFramesProcessed*music.stream.channels;
1763 secondsPlayed = (float)samplesPlayed/(music.stream.sampleRate*music.stream.channels);
1766 return secondsPlayed;
1769 // Init audio stream (to stream audio pcm data)
1770 AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels)
1772 AudioStream stream = { 0 };
1774 stream.sampleRate = sampleRate;
1775 stream.sampleSize = sampleSize;
1776 stream.channels = channels;
1778 ma_format formatIn = ((stream.sampleSize == 8)? ma_format_u8 : ((stream.sampleSize == 16)? ma_format_s16 : ma_format_f32));
1780 // The size of a streaming buffer must be at least double the size of a period
1781 unsigned int periodSize = AUDIO.System.device.playback.internalPeriodSizeInFrames;
1782 unsigned int subBufferSize = GetAudioStreamBufferSizeDefault();
1784 if (subBufferSize < periodSize) subBufferSize = periodSize;
1786 // Create a double audio buffer of defined size
1787 stream.buffer = LoadAudioBuffer(formatIn, stream.channels, stream.sampleRate, subBufferSize*2, AUDIO_BUFFER_USAGE_STREAM);
1789 if (stream.buffer != NULL)
1791 stream.buffer->looping = true; // Always loop for streaming buffers
1792 TRACELOG(LOG_INFO, "STREAM: Initialized successfully (%i Hz, %i bit, %s)", stream.sampleRate, stream.sampleSize, (stream.channels == 1)? "Mono" : "Stereo");
1794 else TRACELOG(LOG_WARNING, "STREAM: Failed to load audio buffer, stream could not be created");
1799 // Close audio stream and free memory
1800 void CloseAudioStream(AudioStream stream)
1802 UnloadAudioBuffer(stream.buffer);
1804 TRACELOG(LOG_INFO, "STREAM: Unloaded audio stream data from RAM");
1807 // Update audio stream buffers with data
1808 // NOTE 1: Only updates one buffer of the stream source: unqueue -> update -> queue
1809 // NOTE 2: To unqueue a buffer it needs to be processed: IsAudioStreamProcessed()
1810 void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount)
1812 if (stream.buffer != NULL)
1814 if (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1])
1816 ma_uint32 subBufferToUpdate = 0;
1818 if (stream.buffer->isSubBufferProcessed[0] && stream.buffer->isSubBufferProcessed[1])
1820 // Both buffers are available for updating.
1821 // Update the first one and make sure the cursor is moved back to the front.
1822 subBufferToUpdate = 0;
1823 stream.buffer->frameCursorPos = 0;
1827 // Just update whichever sub-buffer is processed.
1828 subBufferToUpdate = (stream.buffer->isSubBufferProcessed[0])? 0 : 1;
1831 ma_uint32 subBufferSizeInFrames = stream.buffer->sizeInFrames/2;
1832 unsigned char *subBuffer = stream.buffer->data + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate);
1834 // TODO: Get total frames processed on this buffer... DOES NOT WORK.
1835 stream.buffer->totalFramesProcessed += subBufferSizeInFrames;
1837 // Does this API expect a whole buffer to be updated in one go?
1838 // Assuming so, but if not will need to change this logic.
1839 if (subBufferSizeInFrames >= (ma_uint32)samplesCount/stream.channels)
1841 ma_uint32 framesToWrite = subBufferSizeInFrames;
1843 if (framesToWrite > ((ma_uint32)samplesCount/stream.channels)) framesToWrite = (ma_uint32)samplesCount/stream.channels;
1845 ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8);
1846 memcpy(subBuffer, data, bytesToWrite);
1848 // Any leftover frames should be filled with zeros.
1849 ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite;
1851 if (leftoverFrameCount > 0) memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8));
1853 stream.buffer->isSubBufferProcessed[subBufferToUpdate] = false;
1855 else TRACELOG(LOG_WARNING, "STREAM: Attempting to write too many frames to buffer");
1857 else TRACELOG(LOG_WARNING, "STREAM: Buffer not available for updating");
1861 // Check if any audio stream buffers requires refill
1862 bool IsAudioStreamProcessed(AudioStream stream)
1864 if (stream.buffer == NULL) return false;
1866 return (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1]);
1869 // Play audio stream
1870 void PlayAudioStream(AudioStream stream)
1872 PlayAudioBuffer(stream.buffer);
1875 // Play audio stream
1876 void PauseAudioStream(AudioStream stream)
1878 PauseAudioBuffer(stream.buffer);
1881 // Resume audio stream playing
1882 void ResumeAudioStream(AudioStream stream)
1884 ResumeAudioBuffer(stream.buffer);
1887 // Check if audio stream is playing.
1888 bool IsAudioStreamPlaying(AudioStream stream)
1890 return IsAudioBufferPlaying(stream.buffer);
1893 // Stop audio stream
1894 void StopAudioStream(AudioStream stream)
1896 StopAudioBuffer(stream.buffer);
1899 // Set volume for audio stream (1.0 is max level)
1900 void SetAudioStreamVolume(AudioStream stream, float volume)
1902 SetAudioBufferVolume(stream.buffer, volume);
1905 // Set pitch for audio stream (1.0 is base level)
1906 void SetAudioStreamPitch(AudioStream stream, float pitch)
1908 SetAudioBufferPitch(stream.buffer, pitch);
1911 // Default size for new audio streams
1912 void SetAudioStreamBufferSizeDefault(int size)
1914 AUDIO.Buffer.defaultSize = size;
1917 int GetAudioStreamBufferSizeDefault()
1919 // if the buffer is not set, compute one that would give us a buffer good enough for a decent frame rate
1920 if (AUDIO.Buffer.defaultSize == 0)
1921 AUDIO.Buffer.defaultSize = AUDIO.System.device.sampleRate/30;
1923 return AUDIO.Buffer.defaultSize;
1926 //----------------------------------------------------------------------------------
1927 // Module specific Functions Definition
1928 //----------------------------------------------------------------------------------
1930 // Log callback function
1931 static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message)
1936 TRACELOG(LOG_WARNING, "miniaudio: %s", message); // All log messages from miniaudio are errors
1939 // Reads audio data from an AudioBuffer object in internal format.
1940 static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, void *framesOut, ma_uint32 frameCount)
1942 ma_uint32 subBufferSizeInFrames = (audioBuffer->sizeInFrames > 1)? audioBuffer->sizeInFrames/2 : audioBuffer->sizeInFrames;
1943 ma_uint32 currentSubBufferIndex = audioBuffer->frameCursorPos/subBufferSizeInFrames;
1945 if (currentSubBufferIndex > 1) return 0;
1947 // Another thread can update the processed state of buffers so
1948 // we just take a copy here to try and avoid potential synchronization problems
1949 bool isSubBufferProcessed[2];
1950 isSubBufferProcessed[0] = audioBuffer->isSubBufferProcessed[0];
1951 isSubBufferProcessed[1] = audioBuffer->isSubBufferProcessed[1];
1953 ma_uint32 frameSizeInBytes = ma_get_bytes_per_frame(audioBuffer->converter.config.formatIn, audioBuffer->converter.config.channelsIn);
1955 // Fill out every frame until we find a buffer that's marked as processed. Then fill the remainder with 0
1956 ma_uint32 framesRead = 0;
1959 // We break from this loop differently depending on the buffer's usage
1960 // - For static buffers, we simply fill as much data as we can
1961 // - For streaming buffers we only fill the halves of the buffer that are processed
1962 // Unprocessed halves must keep their audio data in-tact
1963 if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC)
1965 if (framesRead >= frameCount) break;
1969 if (isSubBufferProcessed[currentSubBufferIndex]) break;
1972 ma_uint32 totalFramesRemaining = (frameCount - framesRead);
1973 if (totalFramesRemaining == 0) break;
1975 ma_uint32 framesRemainingInOutputBuffer;
1976 if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC)
1978 framesRemainingInOutputBuffer = audioBuffer->sizeInFrames - audioBuffer->frameCursorPos;
1982 ma_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames*currentSubBufferIndex;
1983 framesRemainingInOutputBuffer = subBufferSizeInFrames - (audioBuffer->frameCursorPos - firstFrameIndexOfThisSubBuffer);
1986 ma_uint32 framesToRead = totalFramesRemaining;
1987 if (framesToRead > framesRemainingInOutputBuffer) framesToRead = framesRemainingInOutputBuffer;
1989 memcpy((unsigned char *)framesOut + (framesRead*frameSizeInBytes), audioBuffer->data + (audioBuffer->frameCursorPos*frameSizeInBytes), framesToRead*frameSizeInBytes);
1990 audioBuffer->frameCursorPos = (audioBuffer->frameCursorPos + framesToRead)%audioBuffer->sizeInFrames;
1991 framesRead += framesToRead;
1993 // If we've read to the end of the buffer, mark it as processed
1994 if (framesToRead == framesRemainingInOutputBuffer)
1996 audioBuffer->isSubBufferProcessed[currentSubBufferIndex] = true;
1997 isSubBufferProcessed[currentSubBufferIndex] = true;
1999 currentSubBufferIndex = (currentSubBufferIndex + 1)%2;
2001 // We need to break from this loop if we're not looping
2002 if (!audioBuffer->looping)
2004 StopAudioBuffer(audioBuffer);
2011 ma_uint32 totalFramesRemaining = (frameCount - framesRead);
2012 if (totalFramesRemaining > 0)
2014 memset((unsigned char *)framesOut + (framesRead*frameSizeInBytes), 0, totalFramesRemaining*frameSizeInBytes);
2016 // For static buffers we can fill the remaining frames with silence for safety, but we don't want
2017 // to report those frames as "read". The reason for this is that the caller uses the return value
2018 // to know whether or not a non-looping sound has finished playback.
2019 if (audioBuffer->usage != AUDIO_BUFFER_USAGE_STATIC) framesRead += totalFramesRemaining;
2025 // Reads audio data from an AudioBuffer object in device format. Returned data will be in a format appropriate for mixing.
2026 static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, float *framesOut, ma_uint32 frameCount)
2028 // What's going on here is that we're continuously converting data from the AudioBuffer's internal format to the mixing format, which
2029 // should be defined by the output format of the data converter. We do this until frameCount frames have been output. The important
2030 // detail to remember here is that we never, ever attempt to read more input data than is required for the specified number of output
2031 // frames. This can be achieved with ma_data_converter_get_required_input_frame_count().
2032 ma_uint8 inputBuffer[4096];
2033 ma_uint32 inputBufferFrameCap = sizeof(inputBuffer)/ma_get_bytes_per_frame(audioBuffer->converter.config.formatIn, audioBuffer->converter.config.channelsIn);
2035 ma_uint32 totalOutputFramesProcessed = 0;
2036 while (totalOutputFramesProcessed < frameCount)
2038 ma_uint64 outputFramesToProcessThisIteration = frameCount - totalOutputFramesProcessed;
2040 ma_uint64 inputFramesToProcessThisIteration = ma_data_converter_get_required_input_frame_count(&audioBuffer->converter, outputFramesToProcessThisIteration);
2041 if (inputFramesToProcessThisIteration > inputBufferFrameCap)
2043 inputFramesToProcessThisIteration = inputBufferFrameCap;
2046 float *runningFramesOut = framesOut + (totalOutputFramesProcessed*audioBuffer->converter.config.channelsOut);
2048 /* At this point we can convert the data to our mixing format. */
2049 ma_uint64 inputFramesProcessedThisIteration = ReadAudioBufferFramesInInternalFormat(audioBuffer, inputBuffer, (ma_uint32)inputFramesToProcessThisIteration); /* Safe cast. */
2050 ma_uint64 outputFramesProcessedThisIteration = outputFramesToProcessThisIteration;
2051 ma_data_converter_process_pcm_frames(&audioBuffer->converter, inputBuffer, &inputFramesProcessedThisIteration, runningFramesOut, &outputFramesProcessedThisIteration);
2053 totalOutputFramesProcessed += (ma_uint32)outputFramesProcessedThisIteration; /* Safe cast. */
2055 if (inputFramesProcessedThisIteration < inputFramesToProcessThisIteration)
2057 break; /* Ran out of input data. */
2060 /* This should never be hit, but will add it here for safety. Ensures we get out of the loop when no input nor output frames are processed. */
2061 if (inputFramesProcessedThisIteration == 0 && outputFramesProcessedThisIteration == 0)
2067 return totalOutputFramesProcessed;
2071 // Sending audio data to device callback function
2072 // NOTE: All the mixing takes place here
2073 static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount)
2077 // Mixing is basically just an accumulation, we need to initialize the output buffer to 0
2078 memset(pFramesOut, 0, frameCount*pDevice->playback.channels*ma_get_bytes_per_sample(pDevice->playback.format));
2080 // Using a mutex here for thread-safety which makes things not real-time
2081 // This is unlikely to be necessary for this project, but may want to consider how you might want to avoid this
2082 ma_mutex_lock(&AUDIO.System.lock);
2084 for (AudioBuffer *audioBuffer = AUDIO.Buffer.first; audioBuffer != NULL; audioBuffer = audioBuffer->next)
2086 // Ignore stopped or paused sounds
2087 if (!audioBuffer->playing || audioBuffer->paused) continue;
2089 ma_uint32 framesRead = 0;
2093 if (framesRead >= frameCount) break;
2095 // Just read as much data as we can from the stream
2096 ma_uint32 framesToRead = (frameCount - framesRead);
2098 while (framesToRead > 0)
2100 float tempBuffer[1024]; // 512 frames for stereo
2102 ma_uint32 framesToReadRightNow = framesToRead;
2103 if (framesToReadRightNow > sizeof(tempBuffer)/sizeof(tempBuffer[0])/AUDIO_DEVICE_CHANNELS)
2105 framesToReadRightNow = sizeof(tempBuffer)/sizeof(tempBuffer[0])/AUDIO_DEVICE_CHANNELS;
2108 ma_uint32 framesJustRead = ReadAudioBufferFramesInMixingFormat(audioBuffer, tempBuffer, framesToReadRightNow);
2109 if (framesJustRead > 0)
2111 float *framesOut = (float *)pFramesOut + (framesRead*AUDIO.System.device.playback.channels);
2112 float *framesIn = tempBuffer;
2114 MixAudioFrames(framesOut, framesIn, framesJustRead, audioBuffer->volume);
2116 framesToRead -= framesJustRead;
2117 framesRead += framesJustRead;
2120 if (!audioBuffer->playing)
2122 framesRead = frameCount;
2126 // If we weren't able to read all the frames we requested, break
2127 if (framesJustRead < framesToReadRightNow)
2129 if (!audioBuffer->looping)
2131 StopAudioBuffer(audioBuffer);
2136 // Should never get here, but just for safety,
2137 // move the cursor position back to the start and continue the loop
2138 audioBuffer->frameCursorPos = 0;
2144 // If for some reason we weren't able to read every frame we'll need to break from the loop
2145 // Not doing this could theoretically put us into an infinite loop
2146 if (framesToRead > 0) break;
2151 ma_mutex_unlock(&AUDIO.System.lock);
2154 // This is the main mixing function. Mixing is pretty simple in this project - it's just an accumulation.
2155 // NOTE: framesOut is both an input and an output. It will be initially filled with zeros outside of this function.
2156 static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume)
2158 for (ma_uint32 iFrame = 0; iFrame < frameCount; ++iFrame)
2160 for (ma_uint32 iChannel = 0; iChannel < AUDIO.System.device.playback.channels; ++iChannel)
2162 float *frameOut = framesOut + (iFrame*AUDIO.System.device.playback.channels);
2163 const float *frameIn = framesIn + (iFrame*AUDIO.System.device.playback.channels);
2165 frameOut[iChannel] += (frameIn[iChannel]*localVolume);
2170 #if defined(SUPPORT_FILEFORMAT_WAV)
2171 // Load WAV file data into Wave structure
2172 // NOTE: Using dr_wav library
2173 static Wave LoadWAV(const unsigned char *fileData, unsigned int fileSize)
2178 bool success = drwav_init_memory(&wav, fileData, fileSize, NULL);
2182 wave.sampleCount = (unsigned int)wav.totalPCMFrameCount*wav.channels;
2183 wave.sampleRate = wav.sampleRate;
2184 wave.sampleSize = 16; // NOTE: We are forcing conversion to 16bit
2185 wave.channels = wav.channels;
2186 wave.data = (short *)RL_MALLOC(wave.sampleCount*sizeof(short));
2187 drwav_read_pcm_frames_s16(&wav, wav.totalPCMFrameCount, wave.data);
2189 else TRACELOG(LOG_WARNING, "WAVE: Failed to load WAV data");
2196 // Save wave data as WAV file
2197 // NOTE: Using dr_wav library
2198 static int SaveWAV(Wave wave, const char *fileName)
2200 int success = false;
2203 drwav_data_format format = { 0 };
2204 format.container = drwav_container_riff;
2205 format.format = DR_WAVE_FORMAT_PCM;
2206 format.channels = wave.channels;
2207 format.sampleRate = wave.sampleRate;
2208 format.bitsPerSample = wave.sampleSize;
2210 void *fileData = NULL;
2211 size_t fileDataSize = 0;
2212 success = drwav_init_memory_write(&wav, &fileData, &fileDataSize, &format, NULL);
2213 if (success) success = (int)drwav_write_pcm_frames(&wav, wave.sampleCount/wave.channels, wave.data);
2214 drwav_result result = drwav_uninit(&wav);
2216 if (result == DRWAV_SUCCESS) success = SaveFileData(fileName, (unsigned char *)fileData, (unsigned int)fileDataSize);
2218 drwav_free(fileData, NULL);
2224 #if defined(SUPPORT_FILEFORMAT_OGG)
2225 // Load OGG file data into Wave structure
2226 // NOTE: Using stb_vorbis library
2227 static Wave LoadOGG(const unsigned char *fileData, unsigned int fileSize)
2231 stb_vorbis *oggData = stb_vorbis_open_memory((unsigned char *)fileData, fileSize, NULL, NULL);
2233 if (oggData != NULL)
2235 stb_vorbis_info info = stb_vorbis_get_info(oggData);
2237 wave.sampleRate = info.sample_rate;
2238 wave.sampleSize = 16; // 16 bit per sample (short)
2239 wave.channels = info.channels;
2240 wave.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples(oggData)*info.channels; // Independent by channel
2242 float totalSeconds = stb_vorbis_stream_length_in_seconds(oggData);
2243 if (totalSeconds > 10) TRACELOG(LOG_WARNING, "WAVE: OGG audio length larger than 10 seconds (%f sec.), that's a big file in memory, consider music streaming", totalSeconds);
2245 wave.data = (short *)RL_MALLOC(wave.sampleCount*sizeof(short));
2247 // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
2248 stb_vorbis_get_samples_short_interleaved(oggData, info.channels, (short *)wave.data, wave.sampleCount);
2249 TRACELOG(LOG_INFO, "WAVE: OGG data loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
2251 stb_vorbis_close(oggData);
2253 else TRACELOG(LOG_WARNING, "WAVE: Failed to load OGG data");
2259 #if defined(SUPPORT_FILEFORMAT_FLAC)
2260 // Load FLAC file data into Wave structure
2261 // NOTE: Using dr_flac library
2262 static Wave LoadFLAC(const unsigned char *fileData, unsigned int fileSize)
2266 // Decode the entire FLAC file in one go
2267 unsigned long long int totalFrameCount = 0;
2268 wave.data = drflac_open_memory_and_read_pcm_frames_s16(fileData, fileSize, &wave.channels, &wave.sampleRate, &totalFrameCount, NULL);
2270 if (wave.data != NULL)
2272 wave.sampleCount = (unsigned int)totalFrameCount*wave.channels;
2273 wave.sampleSize = 16;
2275 TRACELOG(LOG_INFO, "WAVE: FLAC data loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
2277 else TRACELOG(LOG_WARNING, "WAVE: Failed to load FLAC data");
2283 #if defined(SUPPORT_FILEFORMAT_MP3)
2284 // Load MP3 file data into Wave structure
2285 // NOTE: Using dr_mp3 library
2286 static Wave LoadMP3(const unsigned char *fileData, unsigned int fileSize)
2289 drmp3_config config = { 0 };
2291 // Decode the entire MP3 file in one go
2292 unsigned long long int totalFrameCount = 0;
2293 wave.data = drmp3_open_memory_and_read_pcm_frames_f32(fileData, fileSize, &config, &totalFrameCount, NULL);
2295 if (wave.data != NULL)
2297 wave.channels = config.channels;
2298 wave.sampleRate = config.sampleRate;
2299 wave.sampleCount = (int)totalFrameCount*wave.channels;
2300 wave.sampleSize = 32;
2302 // NOTE: Only support up to 2 channels (mono, stereo)
2304 if (wave.channels > 2) TRACELOG(LOG_WARNING, "WAVE: MP3 channels number (%i) not supported", wave.channels);
2306 TRACELOG(LOG_INFO, "WAVE: MP3 file loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
2308 else TRACELOG(LOG_WARNING, "WAVE: Failed to load MP3 data");
2314 // Some required functions for audio standalone module version
2315 #if defined(RAUDIO_STANDALONE)
2316 // Check file extension
2317 static bool IsFileExtension(const char *fileName, const char *ext)
2319 bool result = false;
2320 const char *fileExt;
2322 if ((fileExt = strrchr(fileName, '.')) != NULL)
2324 if (strcmp(fileExt, ext) == 0) result = true;
2330 // Load data from file into a buffer
2331 static unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead)
2333 unsigned char *data = NULL;
2336 if (fileName != NULL)
2338 FILE *file = fopen(fileName, "rb");
2342 // WARNING: On binary streams SEEK_END could not be found,
2343 // using fseek() and ftell() could not work in some (rare) cases
2344 fseek(file, 0, SEEK_END);
2345 int size = ftell(file);
2346 fseek(file, 0, SEEK_SET);
2350 data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
2352 // NOTE: fread() returns number of read elements instead of bytes, so we read [1 byte, size elements]
2353 unsigned int count = (unsigned int)fread(data, sizeof(unsigned char), size, file);
2356 if (count != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded", fileName);
2357 else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
2359 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
2363 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2365 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2370 // Save data to file from buffer
2371 static bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite)
2373 if (fileName != NULL)
2375 FILE *file = fopen(fileName, "wb");
2379 unsigned int count = (unsigned int)fwrite(data, sizeof(unsigned char), bytesToWrite, file);
2381 if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write file", fileName);
2382 else if (count != bytesToWrite) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially written", fileName);
2383 else TRACELOG(LOG_INFO, "FILEIO: [%s] File saved successfully", fileName);
2387 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2389 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2392 // Save text data to file (write), string must be '\0' terminated
2393 static bool SaveFileText(const char *fileName, char *text)
2395 if (fileName != NULL)
2397 FILE *file = fopen(fileName, "wt");
2401 int count = fprintf(file, "%s", text);
2403 if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write text file", fileName);
2404 else TRACELOG(LOG_INFO, "FILEIO: [%s] Text file saved successfully", fileName);
2408 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
2410 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");