mirror of
https://github.com/libsdl-org/SDL.git
synced 2025-10-16 23:06:03 +00:00
Add SDL_ConvertAudioSamples() helper function
This commit is contained in:
@@ -1662,3 +1662,73 @@ void SDL_CalculateAudioSpec(SDL_AudioSpec *spec)
|
||||
spec->size *= spec->samples;
|
||||
}
|
||||
|
||||
int SDL_ConvertAudioSamples(
|
||||
SDL_AudioFormat src_format, Uint8 src_channels, int src_rate, int src_len, Uint8 *src_data,
|
||||
SDL_AudioFormat dst_format, Uint8 dst_channels, int dst_rate, int *dst_len, Uint8 **dst_data)
|
||||
{
|
||||
int ret = -1;
|
||||
SDL_AudioStream *stream = NULL;
|
||||
|
||||
int src_samplesize, dst_samplesize;
|
||||
int real_dst_len;
|
||||
|
||||
|
||||
if (src_len < 0) {
|
||||
return SDL_InvalidParamError("src_len");
|
||||
}
|
||||
if (src_data == NULL) {
|
||||
return SDL_InvalidParamError("src_data");
|
||||
}
|
||||
if (dst_len == NULL) {
|
||||
return SDL_InvalidParamError("dst_len");
|
||||
}
|
||||
if (dst_data == NULL) {
|
||||
return SDL_InvalidParamError("dst_data");
|
||||
}
|
||||
|
||||
*dst_len = 0;
|
||||
*dst_data = NULL;
|
||||
|
||||
stream = SDL_CreateAudioStream(src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate);
|
||||
if (stream == NULL) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
src_samplesize = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels;
|
||||
dst_samplesize = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels;
|
||||
|
||||
src_len &= ~(src_samplesize - 1);
|
||||
*dst_len = dst_samplesize * (src_len / src_samplesize);
|
||||
if (src_rate < dst_rate) {
|
||||
const double mult = ((double)dst_rate) / ((double)src_rate);
|
||||
*dst_len *= (int) SDL_ceil(mult);
|
||||
}
|
||||
|
||||
*dst_len &= ~(dst_samplesize - 1);
|
||||
*dst_data = (Uint8 *)SDL_malloc(*dst_len);
|
||||
if (*dst_data == NULL) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
if (SDL_PutAudioStreamData(stream, src_data, src_len) < 0 ||
|
||||
SDL_FlushAudioStream(stream) < 0) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
real_dst_len = SDL_GetAudioStreamData(stream, *dst_data, *dst_len);
|
||||
if (real_dst_len < 0) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
*dst_len = real_dst_len;
|
||||
ret = 0;
|
||||
|
||||
end:
|
||||
if (ret != 0) {
|
||||
SDL_free(*dst_data);
|
||||
*dst_len = 0;
|
||||
*dst_data = NULL;
|
||||
}
|
||||
SDL_DestroyAudioStream(stream);
|
||||
return ret;
|
||||
}
|
||||
|
Reference in New Issue
Block a user