/** * \brief Builds various audio conversion structures * * \sa https://wiki.libsdl.org/SDL_BuildAudioCVT */ int audio_buildAudioCVT() { int result; SDL_AudioCVT cvt; SDL_AudioSpec spec1; SDL_AudioSpec spec2; int i, ii, j, jj, k, kk; /* No conversion needed */ spec1.format = AUDIO_S16LSB; spec1.channels = 2; spec1.freq = 22050; result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq, spec1.format, spec1.channels, spec1.freq); SDLTest_AssertPass("Call to SDL_BuildAudioCVT(spec1 ==> spec1)"); SDLTest_AssertCheck(result == 0, "Verify result value; expected: 0, got: %i", result); /* Typical conversion */ spec1.format = AUDIO_S8; spec1.channels = 1; spec1.freq = 22050; spec2.format = AUDIO_S16LSB; spec2.channels = 2; spec2.freq = 44100; result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq, spec2.format, spec2.channels, spec2.freq); SDLTest_AssertPass("Call to SDL_BuildAudioCVT(spec1 ==> spec2)"); SDLTest_AssertCheck(result == 1, "Verify result value; expected: 1, got: %i", result); /* All source conversions with random conversion targets, allow 'null' conversions */ for (i = 0; i < _numAudioFormats; i++) { for (j = 0; j < _numAudioChannels; j++) { for (k = 0; k < _numAudioFrequencies; k++) { spec1.format = _audioFormats[i]; spec1.channels = _audioChannels[j]; spec1.freq = _audioFrequencies[k]; ii = SDLTest_RandomIntegerInRange(0, _numAudioFormats - 1); jj = SDLTest_RandomIntegerInRange(0, _numAudioChannels - 1); kk = SDLTest_RandomIntegerInRange(0, _numAudioFrequencies - 1); spec2.format = _audioFormats[ii]; spec2.channels = _audioChannels[jj]; spec2.freq = _audioFrequencies[kk]; result = SDL_BuildAudioCVT(&cvt, spec1.format, spec1.channels, spec1.freq, spec2.format, spec2.channels, spec2.freq); SDLTest_AssertPass("Call to SDL_BuildAudioCVT(format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i ==> format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i)", i, _audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, _audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq); SDLTest_AssertCheck(result == 0 || result == 1, "Verify result value; expected: 0 or 1, got: %i", result); if (result<0) { SDLTest_LogError("%s", SDL_GetError()); } else { SDLTest_AssertCheck(cvt.len_mult > 0, "Verify that cvt.len_mult value; expected: >0, got: %i", cvt.len_mult); } } } } return TEST_COMPLETED; }
////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CSound::CSound(char *filename, int iSoundID) { m_iSoundID = iSoundID; Uint32 len; if (SDL_LoadWAV(filename, &m_spec, &m_data, &len) == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n",filename, SDL_GetError()); m_len = CSoundTime(0); return; } m_len = CSoundTime(len); m_pos = CSoundTime(0); CEasySound *es = CEasySound::Instance(); SDL_AudioSpec obtained = es->GetObtained(); SDL_AudioCVT cvt; SDL_BuildAudioCVT(&cvt, m_spec.format, m_spec.channels, m_spec.freq, obtained.format, obtained.channels, obtained.freq); cvt.buf = (Uint8*)malloc(m_len.GetSDLTime() * cvt.len_mult); memcpy(cvt.buf, m_data, m_len.GetSDLTime()); cvt.len = m_len.GetSDLTime(); SDL_ConvertAudio(&cvt); SDL_FreeWAV(m_data); SDL_LockAudio(); m_data = cvt.buf; // the new length of sound after convert from 8bit to 16bit m_len = CSoundTime( cvt.len_cvt ); m_pos = CSoundTime( 0 ); SDL_UnlockAudio(); }
/* * Play-time conversion. Performs output conversion only once per sound effect used. * Once the sound sample has been converted, it is cached in SoundChunks[] */ void mixdigi_convert_sound(int i) { SDL_AudioCVT cvt; Uint8 *data = GameSounds[i].data; Uint32 dlen = GameSounds[i].length; int freq = GameSounds[i].freq; //int bits = GameSounds[i].bits; if (SoundChunks[i].abuf) return; //proceed only if not converted yet if (data) { if (MIX_DIGI_DEBUG) con_printf(CON_DEBUG,"converting %d (%d)\n", i, dlen); SDL_BuildAudioCVT(&cvt, AUDIO_U8, 1, freq, MIX_OUTPUT_FORMAT, MIX_OUTPUT_CHANNELS, digi_sample_rate); cvt.buf = malloc(dlen * cvt.len_mult); cvt.len = dlen; memcpy(cvt.buf, data, dlen); if (SDL_ConvertAudio(&cvt)) con_printf(CON_DEBUG,"conversion of %d failed\n", i); SoundChunks[i].abuf = cvt.buf; SoundChunks[i].alen = dlen * cvt.len_mult; SoundChunks[i].allocated = 1; SoundChunks[i].volume = 128; // Max volume = 128 } }
void makeAudio(int i, const char* filename, unsigned char repeat, float volume){ Audio* a = audios + i; if (SDL_LoadWAV(filename, &(a->spec), &(a->sounddata), &(a->soundlength)) == NULL) { printf("Erreur lors du chargement du fichier son: %s\n", SDL_GetError()); return; } if (SDL_BuildAudioCVT(&(a->audioConverter), a->spec.format, a->spec.channels, a->spec.freq, audioSpec.currentConfig.format, audioSpec.currentConfig.channels, audioSpec.currentConfig.freq) < 0) { printf("Impossible de construire le convertisseur audio!\n"); return; } a->audioConverter.buf = malloc(a->soundlength * a->audioConverter.len_mult); a->audioConverter.len = a->soundlength; memcpy(a->audioConverter.buf, a->sounddata, a->soundlength); if (SDL_ConvertAudio(&(a->audioConverter)) != 0) { printf("Erreur lors de la conversion du fichier audio: %s\n", SDL_GetError()); return; } SDL_FreeWAV(a->sounddata); a->sounddata = malloc(a->audioConverter.len_cvt); memcpy(a->sounddata, a->audioConverter.buf, a->audioConverter.len_cvt); free(a->audioConverter.buf); a->soundlength = a->audioConverter.len_cvt; a->soundpos = 0; a->repeat = repeat; a->currentVolume = 0; a->maxVolume = volume; a->play = a->fadeIn = a->fadeOut = 0; }
/* loads a wav file (stored in 'file'), converts it to the mixer's output format, and stores the resulting buffer and length in the sound structure */ void loadSound(const char *file, struct sound *s) { SDL_AudioSpec spec; /* the audio format of the .wav file */ SDL_AudioCVT cvt; /* used to convert .wav to output format when formats differ */ int result; if (SDL_LoadWAV(file, &spec, &s->buffer, &s->length) == NULL) { fatalError("could not load .wav"); } /* build the audio converter */ result = SDL_BuildAudioCVT(&cvt, spec.format, spec.channels, spec.freq, mixer.outputSpec.format, mixer.outputSpec.channels, mixer.outputSpec.freq); if (result == -1) { fatalError("could not build audio CVT"); } else if (result != 0) { /* this happens when the .wav format differs from the output format. we convert the .wav buffer here */ cvt.buf = (Uint8 *) SDL_malloc(s->length * cvt.len_mult); /* allocate conversion buffer */ cvt.len = s->length; /* set conversion buffer length */ SDL_memcpy(cvt.buf, s->buffer, s->length); /* copy sound to conversion buffer */ if (SDL_ConvertAudio(&cvt) == -1) { /* convert the sound */ fatalError("could not convert .wav"); } SDL_free(s->buffer); /* free the original (unconverted) buffer */ s->buffer = cvt.buf; /* point sound buffer to converted buffer */ s->length = cvt.len_cvt; /* set sound buffer's new length */ } }
/* This function loads a sound with SDL_LoadWAV and converts it to the specified sample format. Returns 0 on success and 1 on failure. */ int LoadAndConvertSound(char *filename, SDL_AudioSpec *spec, sound_p sound) { SDL_AudioCVT cvt; /* format conversion structure */ SDL_AudioSpec loaded; /* format of the loaded data */ Uint8 *new_buf; /* Load the WAV file in its original sample format. */ if (SDL_LoadWAV(filename, &loaded, &sound->samples, &sound->length) == NULL) { printf("Unable to load sound: %s\n", SDL_GetError()); return 1; } /* Build a conversion structure for converting the samples. This structure contains the data SDL needs to quickly convert between sample formats. */ if (SDL_BuildAudioCVT(&cvt, loaded.format, loaded.channels, loaded.freq, spec->format, spec->channels, spec->freq) < 0) { printf("Unable to convert sound: %s\n", SDL_GetError()); return 1; } /* Since converting PCM samples can result in more data (for instance, converting 8-bit mono to 16-bit stereo), we need to allocate a new buffer for the converted data. Fortunately SDL_BuildAudioCVT supplied the necessary information. */ cvt.len = sound->length; new_buf = (Uint8 *) malloc(cvt.len * cvt.len_mult); if (new_buf == NULL) { printf("Memory allocation failed.\n"); SDL_FreeWAV(sound->samples); return 1; } /* Copy the sound samples into the new buffer. */ memcpy(new_buf, sound->samples, sound->length); /* Perform the conversion on the new buffer. */ cvt.buf = new_buf; if (SDL_ConvertAudio(&cvt) < 0) { printf("Audio conversion error: %s\n", SDL_GetError()); free(new_buf); SDL_FreeWAV(sound->samples); return 1; } /* Swap the converted data for the original. */ SDL_FreeWAV(sound->samples); sound->samples = new_buf; sound->length = sound->length * cvt.len_mult; /* Success! */ printf("’%s’ was loaded and converted successfully.\n", filename); return 0; }
static void LoadSound(int index, char *file) { SDL_AudioSpec wave; Uint8 *data; Uint32 dlen; SDL_AudioCVT cvt; /* Load the sound file and convert it to 16-bit stereo at 22kHz */ if (SDL_LoadWAV(file, &wave, &data, &dlen) == NULL) { fprintf(stderr, "Couldn't load %s: %s\n", file, SDL_GetError()); return; } SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 44100); cvt.buf = malloc(dlen*cvt.len_mult); memcpy(cvt.buf, data, dlen); cvt.len = dlen; SDL_ConvertAudio(&cvt); SDL_FreeWAV(data); if (sounds[index].data) { free(sounds[index].data); } SDL_LockAudio(); sounds[index].data = cvt.buf; sounds[index].dlen = cvt.len_cvt; sounds[index].dpos = cvt.len_cvt; SDL_UnlockAudio(); }
bool init_audio( void ) { if (audio_disabled) return false; SDL_AudioSpec ask, got; ask.freq = freq; ask.format = (BYTES_PER_SAMPLE == 2) ? AUDIO_S16SYS : AUDIO_S8; ask.channels = 1; ask.samples = 512; ask.callback = audio_cb; printf("\trequested %d Hz, %d channels, %d samples\n", ask.freq, ask.channels, ask.samples); if (SDL_OpenAudio(&ask, &got) == -1) { fprintf(stderr, "error: failed to initialize SDL audio: %s\n", SDL_GetError()); audio_disabled = true; return false; } printf("\tobtained %d Hz, %d channels, %d samples\n", got.freq, got.channels, got.samples); SDL_BuildAudioCVT(&audio_cvt, ask.format, ask.channels, ask.freq, got.format, got.channels, got.freq); opl_init(); SDL_PauseAudio(0); // unpause return true; }
//Play sound straight from file void cSound::PlaySound(char *file) { if(gGameWorld.gMenu.m_sound == 0){return;} SDL_AudioSpec wave; Uint8 *data; Uint32 dlen; SDL_AudioCVT cvt; /* Load the sound file and convert it to 16-bit stereo at 22kHz */ if(SDL_LoadWAV(file, &wave, &data, &dlen) == NULL){return;} SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 22050); cvt.buf = (Uint8*)malloc(dlen*cvt.len_mult); memcpy(cvt.buf, data, dlen); cvt.len = dlen; SDL_ConvertAudio(&cvt); SDL_FreeWAV(data); /* Put the sound data in the slot (it starts playing immediately) */ if(snd.data != NULL){free(snd.data);} SDL_LockAudio(); snd.data = cvt.buf; snd.dlen = cvt.len_cvt; snd.dpos = 0; SDL_UnlockAudio(); }
bool Audio::CVT::Build(const Audio::Spec & src, const Audio::Spec & dst) { if(1 == SDL_BuildAudioCVT(this, src.format, src.channels, src.freq, dst.format, dst.channels, dst.freq)) return true; std::cerr << "Audio::CVT::Build: " << SDL_GetError() << std::endl; return false; }
void Audio_new_cvt (SDL_AudioCVT* cvt, SDL_AudioFormat format, Uint8 channels, int freq) { SDL_BuildAudioCVT( cvt, format, channels, freq, _audio.spec.format, _audio.spec.channels, _audio.spec.freq ); }
// This function loads a sound with SDL_LoadWAV and converts // it to the specified sample format. void Sound::loadAndConvertSound(char *filename, SDL_AudioSpec spec) { SDL_AudioCVT cvt; // audio format conversion structure SDL_AudioSpec loaded; // format of the loaded data Uint8 *new_buf; // Load the WAV file in its original sample format. if (SDL_LoadWAV(filename, &loaded, &samples, &length) == NULL) { std::cout << "Unable to load sound: " << SDL_GetError() << std::endl; // throw string("Unable to load sound: ") + string(SDL_GetError()); } // Build a conversion structure for converting the samples. // This structure contains the data SDL needs to quickly // convert between sample formats. if (SDL_BuildAudioCVT(&cvt, loaded.format, loaded.channels, loaded.freq, spec.format, spec.channels, spec.freq) < 0) { std::cout << "Unable to convert sound: " << SDL_GetError() << std::endl; // throw string("Unable to convert sound: ") + string(SDL_GetError()); } // Since converting PCM samples can result in more data // (for instance, converting 8-bit mono to 16-bit stereo), // we need to allocate a new buffer for the converted data. // Fortunately SDL_BuildAudioCVT supplied the necessary // information. cvt.len = length; new_buf = (Uint8 *) malloc(cvt.len * cvt.len_mult); if (new_buf == NULL) { SDL_FreeWAV(samples); std::cout << "Memory allocation failed." << std::endl; // throw string("Memory allocation failed."); } // Copy the sound samples into the new buffer. memcpy(new_buf, samples, length); // Perform the conversion on the new buffer. cvt.buf = new_buf; if (SDL_ConvertAudio(&cvt) < 0) { free(new_buf); SDL_FreeWAV(samples); std::cout << "Audio conversion error: " << SDL_GetError() << std::endl; // throw string("Audio conversion error: ") + string(SDL_GetError()); } // Swap the converted data for the original. SDL_FreeWAV(samples); samples = new_buf; length = length * cvt.len_mult; // Success! printf("'%s' was loaded and converted successfully.\n", filename); }
static void pcm_dma_apply_settings_nolock(void) { cvt_status = SDL_BuildAudioCVT(&cvt, AUDIO_S16SYS, 2, pcm_sampr, obtained.format, obtained.channels, obtained.freq); if (cvt_status < 0) { cvt.len_ratio = (double)obtained.freq / (double)pcm_sampr; } }
void Jukebox::PlayZAttack() //Function to play the background theme song specifically. { const char *file = Z_ATTACK_SOUND; int index; SDL_AudioSpec wave; Uint8 *data; Uint32 dlen; SDL_AudioCVT cvt; //Look for an empty (or finished) sound slot for ( index=0; index<NUM_SOUNDS; ++index ) { if ( sounds[index].dpos == sounds[index].dlen ) { break; } } if ( index == NUM_SOUNDS ) { return; } // Load the sound file and convert it to 16-bit stereo at 22kHz if ( SDL_LoadWAV(file, &wave, &data, &dlen) == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n", file, SDL_GetError()); return; } SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 22050); cvt.buf = (Uint8*)malloc(dlen*cvt.len_mult); memcpy(cvt.buf, data, dlen); cvt.len = dlen; SDL_ConvertAudio(&cvt); SDL_FreeWAV(data); // Put the sound data in the slot (it starts playing immediately) if (sounds[index].data) { free(sounds[index].data); } SDL_LockAudio(); sounds[index].data = cvt.buf; sounds[index].dlen = cvt.len_cvt; sounds[index].dpos = 0; SDL_UnlockAudio(); }
static void ExpandSoundData(byte *data, int samplerate, int length, Mix_Chunk *destination) { SDL_AudioCVT convertor; if (samplerate <= mixer_freq && ConvertibleRatio(samplerate, mixer_freq) && SDL_BuildAudioCVT(&convertor, AUDIO_U8, 1, samplerate, mixer_format, mixer_channels, mixer_freq)) { convertor.buf = destination->abuf; convertor.len = length; memcpy(convertor.buf, data, length); SDL_ConvertAudio(&convertor); } else { Sint16 *expanded = (Sint16 *) destination->abuf; int expanded_length; int expand_ratio; int i; // Generic expansion if conversion does not work: // // SDL's audio conversion only works for rate conversions that are // powers of 2; if the two formats are not in a direct power of 2 // ratio, do this naive conversion instead. // number of samples in the converted sound expanded_length = ((uint64_t) length * mixer_freq) / samplerate; expand_ratio = (length << 8) / expanded_length; for (i=0; i<expanded_length; ++i) { Sint16 sample; int src; src = (i * expand_ratio) >> 8; sample = data[src] | (data[src] << 8); sample -= 32768; // expand 8->16 bits, mono->stereo expanded[i * 2] = expanded[i * 2 + 1] = sample; } } }
bool COGGPlayer::open() { // If Ogg detected, decode it into the stream psound->sound_buffer. // It must fit into the Audio_cvt structure, so that it can be converted mHasCommonFreqBase = true; if(ov_fopen((char*)GetFullFileName(m_filename).c_str(), &m_oggStream) != 0) return false; mVorbisInfo = ov_info(&m_oggStream, -1); ov_comment(&m_oggStream, -1); m_AudioFileSpec.format = AUDIO_S16LSB; // Ogg Audio seems to always use this format m_AudioFileSpec.channels = mVorbisInfo->channels; m_AudioFileSpec.freq = mVorbisInfo->rate; // Since I cannot convert with a proper quality from 44100 to 48000 Ogg wave output // we set m_AudioFileSpec frequency to the same as the one of the SDL initialized AudioSpec // scale just the buffer using readOGGStreamAndResample. // This is base problem, but we have workarounds for that... if( (m_AudioFileSpec.freq%m_AudioSpec.freq != 0) && (m_AudioSpec.freq%m_AudioFileSpec.freq != 0) ) { m_AudioFileSpec.freq = m_AudioSpec.freq; mHasCommonFreqBase = false; } m_pcm_size = ov_pcm_total(&m_oggStream,-1); m_pcm_size *= (mVorbisInfo->channels*sizeof(Sint16)); m_music_pos = 0; g_pLogFile->ftextOut("OGG-Player: File \"%s\" was opened successfully!<br>", m_filename.c_str()); int ret = SDL_BuildAudioCVT(&m_Audio_cvt, m_AudioFileSpec.format, m_AudioFileSpec.channels, m_AudioFileSpec.freq, m_AudioSpec.format, m_AudioSpec.channels, m_AudioSpec.freq); if(ret == -1) return false; const size_t length = m_AudioSpec.size; //m_Audio_cvt.len = (length*m_Audio_cvt.len_mult)/m_Audio_cvt.len_ratio; m_Audio_cvt.len = (length)/m_Audio_cvt.len_ratio; m_Audio_cvt.len = (m_Audio_cvt.len>>2)<<2; m_Audio_cvt.buf = new Uint8[m_Audio_cvt.len*m_Audio_cvt.len_mult]; return true; }
SDL_AudioCVT *SOUND_LoadWAV(const char *filename) { SDL_AudioCVT *wavecvt; SDL_AudioSpec wavespec, *loaded; unsigned char *buf; unsigned int len; if (!g_fAudioOpened) { return NULL; } wavecvt = (SDL_AudioCVT *)malloc(sizeof(SDL_AudioCVT)); if (wavecvt == NULL) { return NULL; } loaded = SDL_LoadWAV_RW(SDL_RWFromFile(filename, "rb"), 1, &wavespec, &buf, &len); if (loaded == NULL) { free(wavecvt); return NULL; } // Build the audio converter and create conversion buffers if (SDL_BuildAudioCVT(wavecvt, wavespec.format, wavespec.channels, wavespec.freq, audio_spec.format, audio_spec.channels, audio_spec.freq) < 0) { SDL_FreeWAV(buf); free(wavecvt); return NULL; } int samplesize = ((wavespec.format & 0xFF) / 8) * wavespec.channels; wavecvt->len = len & ~(samplesize - 1); wavecvt->buf = (unsigned char *)malloc(wavecvt->len * wavecvt->len_mult); if (wavecvt->buf == NULL) { SDL_FreeWAV(buf); free(wavecvt); return NULL; } memcpy(wavecvt->buf, buf, len); SDL_FreeWAV(buf); // Run the audio converter if (SDL_ConvertAudio(wavecvt) < 0) { free(wavecvt->buf); free(wavecvt); return NULL; } return wavecvt; }
/* Callback for SDL Mixer */ void sdlmixer_fill_audio(int channel) { if (Callback_Stop == TRUE) { // free things and //stop calling backs... if (chunk) Mix_FreeChunk(chunk); Log("stop playing back psg\n"); return; } UChar lvol, rvol; int i; # if 0 //LUDO: TO_BE_DONE if (!(cvt.len)) { //once only ? memset(stream,0,sbuf_size*host.sound.stereo); if (!SDL_BuildAudioCVT (&cvt, AUDIO_U8, host.sound.stereo, host.sound.freq, AUDIO_S16, 2, host.sound.freq)) { Log("SDL_BuildAudioCVT failed...audio callback stopped.\n"); return;//#warning: avoid leaving without calling again ? } Log("SDL_BuildAudioCVT init ok.\n"); cvt.len = sbuf_size*host.sound.stereo; cvt.buf = (Uint8*) malloc(cvt.len*cvt.len_mult); //for in place conversion } # endif for (i = 0; i < 6; i++) WriteBuffer_44K(sbuf[i], i, cvt.len); # if 0 //LUDO: TO_BE_DONE ! write_adpcm(); # endif // Adjust the final post-mixed left/right volumes. 0-15 * 1.22 comes out to // (0..18) which when multiplied by the ((-127..127) * 7) we get in the final // stream mix below we have (-16002..16002) which we then divide by 128 to get // a nice unsigned 8-bit value of 128 + (-125..125). if (host.sound.stereo) { lvol = (io.psg_volume >> 4) * 1.22; rvol = (io.psg_volume & 0x0F) * 1.22; }
static void loadSampleJob( void* data ) { if( data == NULL ) { llog( LOG_ERROR, "NULL data passed into loadSampleJob!" ); return; } ThreadedSoundLoadData* loadData = (ThreadedSoundLoadData*)data; // read the entire file into memory and decode it int channels; int rate; short* buffer; int numSamples = stb_vorbis_decode_filename( loadData->fileName, &channels, &rate, &buffer ); if( numSamples < 0 ) { llog( LOG_ERROR, "Error decoding sound sample %s", loadData->fileName ); goto error; } // convert it if( SDL_BuildAudioCVT( &( loadData->loadConverter ), AUDIO_S16, (Uint8)channels, rate, WORKING_FORMAT, loadData->desiredChannels, WORKING_RATE ) < 0 ) { llog( LOG_ERROR, "Unable to create converter for sound." ); goto error; } loadData->loadConverter.len = numSamples * channels * sizeof( buffer[0] ); size_t totLen = loadData->loadConverter.len * loadData->loadConverter.len_mult; if( loadData->loadConverter.len_mult > 1 ) { buffer = mem_Resize( buffer, loadData->loadConverter.len * loadData->loadConverter.len_mult ); // need to make sure there's enough room if( buffer == NULL ) { llog( LOG_ERROR, "Unable to allocate more memory for converting." ); goto error; } } loadData->loadConverter.buf = (Uint8*)buffer; SDL_ConvertAudio( &( loadData->loadConverter ) ); jq_AddMainThreadJob( bindSampleJob, (void*)loadData ); return; error: cleanUpThreadedSoundLoadData( loadData ); }
int playAudio(char *file, int loop){ int index; SDL_AudioSpec wave; Uint8 *data; Uint32 dlen; SDL_AudioCVT cvt; /* Look for an empty (or finished) sound slot */ for ( index=0; index<SOINU_KOPURUA; ++index ) { if ( soinuak[index].dpos == soinuak[index].dlen && !soinuak[index].isLoop) { break; } } if ( index == SOINU_KOPURUA ) return; /* Load the sound file and convert it to 16-bit stereo at 22kHz */ if ( SDL_LoadWAV(file, &wave, &data, &dlen) == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n", file, SDL_GetError()); return; } SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 22050); cvt.buf =(Uint8*) ( malloc(dlen*cvt.len_mult)); memcpy(cvt.buf, data, dlen); cvt.len = dlen; SDL_ConvertAudio(&cvt); SDL_FreeWAV(data); /* Put the sound data in the slot (it starts playing immediately) */ if ( soinuak[index].data ) { free(soinuak[index].data); } SDL_LockAudio(); soinuak[index].id = index; soinuak[index].data = cvt.buf; soinuak[index].dlen = cvt.len_cvt; soinuak[index].dpos = 0; if (loop){ soinuak[index].isLoop = 1; }else{ soinuak[index].isLoop = 0; } SDL_UnlockAudio(); return index; }
/* Read some Ogg stream data and convert it for output */ static void OGG_getsome(OGG_music *music) { int section; int len; char data[4096]; SDL_AudioCVT *cvt; #ifdef OGG_USE_TREMOR len = vorbis.ov_read(&music->vf, data, sizeof(data), §ion); #else len = vorbis.ov_read(&music->vf, data, sizeof(data), 0, 2, 1, §ion); #endif if ( len <= 0 ) { if ( len == 0 ) { music->playing = 0; } return; } cvt = &music->cvt; if ( section != music->section ) { vorbis_info *vi; vi = vorbis.ov_info(&music->vf, -1); SDL_BuildAudioCVT(cvt, AUDIO_S16, vi->channels, vi->rate, mixer.format,mixer.channels,mixer.freq); if ( cvt->buf ) { SDL_free(cvt->buf); } cvt->buf = (Uint8 *)SDL_malloc(sizeof(data)*cvt->len_mult); music->section = section; } if ( cvt->buf ) { memcpy(cvt->buf, data, len); if ( cvt->needed ) { cvt->len = len; SDL_ConvertAudio(cvt); } else { cvt->len_cvt = len; } music->len_available = music->cvt.len_cvt; music->snd_available = music->cvt.buf; } else { SDL_SetError("Out of memory"); music->playing = 0; } }
void audio_initAudioFormat(unsigned int SampleRate, unsigned short SampleSizeInBits, unsigned short Channels){ SDL_Init(SDL_INIT_AUDIO); wanted.freq = SampleRate; wanted.format = audio_checkFormat(SampleSizeInBits); wanted.channels = Channels; wanted.samples = 1024; /* Good low-latency value for callback */ wanted.callback = audio_fill; wanted.userdata = NULL; if ( SDL_OpenAudio(&wanted, NULL) < 0 ) { fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); return; } SDL_PauseAudio(1); SDL_BuildAudioCVT(&cvt, audio_checkFormat(SampleSizeInBits), Channels, SampleRate, wanted.format, wanted.channels, wanted.freq); audio_chunk = (Uint8 *)malloc(audio_len * sizeof(Uint8)); memset(audio_chunk, 0, audio_len); }
void loadsound(const char *s,int num) { SDL_AudioSpec spec; Uint8 *buffer; Uint32 len; SDL_AudioCVT cvt; SDL_AudioSpec *sound=SDL_LoadWAV(s,&spec,&buffer,&len); if(!sound) error("can't open sound file %s: %s\n",s,SDL_GetError()); /* convert sound to 16-bit stereo, 44khz */ SDL_BuildAudioCVT(&cvt,spec.format,spec.channels,spec.freq,AUDIO_S16,2,FREQ); cvt.buf=(Uint8 *)malloc(len*cvt.len_mult); memcpy(cvt.buf,buffer,len); cvt.len=len; SDL_ConvertAudio(&cvt); sounds[num].buffer=buffer; sounds[num].len=len; sounds[num].loop=0; SDL_FreeWAV(buffer); }
/* Once the frame has been read, copies its samples into the output buffer. */ static void decode_frame(mad_data *mp3_mad) { struct mad_pcm *pcm; unsigned int nchannels, nsamples; mad_fixed_t const *left_ch, *right_ch; unsigned char *out; int ret; mad_synth_frame(&mp3_mad->synth, &mp3_mad->frame); pcm = &mp3_mad->synth.pcm; out = mp3_mad->output_buffer + mp3_mad->output_end; if ((mp3_mad->status & MS_cvt_decoded) == 0) { mp3_mad->status |= MS_cvt_decoded; /* The first frame determines some key properties of the stream. In particular, it tells us enough to set up the convert structure now. */ SDL_BuildAudioCVT(&mp3_mad->cvt, AUDIO_S16, pcm->channels, mp3_mad->frame.header.samplerate, mp3_mad->mixer.format, mp3_mad->mixer.channels, mp3_mad->mixer.freq); } /* pcm->samplerate contains the sampling frequency */ nchannels = pcm->channels; nsamples = pcm->length; left_ch = pcm->samples[0]; right_ch = pcm->samples[1]; while (nsamples--) { signed int sample; /* output sample(s) in 16-bit signed little-endian PCM */ sample = scale(*left_ch++); *out++ = ((sample >> 0) & 0xff); *out++ = ((sample >> 8) & 0xff); if (nchannels == 2) { sample = scale(*right_ch++); *out++ = ((sample >> 0) & 0xff); *out++ = ((sample >> 8) & 0xff); } }
void PlaySound(char *file) { int index; SDL_AudioSpec wave; Uint8 *data; Uint32 dlen; SDL_AudioCVT cvt; /* Look for an empty (or finished) sound slot */ for ( index=0; index<NUM_SOUNDS; ++index ) { if ( sounds[index].dpos == sounds[index].dlen ) { break; } } if ( index == NUM_SOUNDS ) return; /* Load the sound file and convert it to 16-bit stereo at 22kHz */ if ( SDL_LoadWAV(file, &wave, &data, &dlen) == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n", file, SDL_GetError()); return; } printf("channels=%d, freq=%d\n", wave.channels, wave.freq); SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 22050); cvt.buf = malloc(dlen*cvt.len_mult); memcpy(cvt.buf, data, dlen); cvt.len = dlen; SDL_ConvertAudio(&cvt); SDL_FreeWAV(data); /* Put the sound data in the slot (it starts playing immediately) */ if ( sounds[index].data ) { free(sounds[index].data); } SDL_LockAudio(); sounds[index].data = cvt.buf; sounds[index].dlen = cvt.len_cvt; sounds[index].dpos = 0; SDL_UnlockAudio(); }
void load_snd(char *file[]){ int i; SDL_AudioSpec wave; Uint8 *data; Uint32 dlen; for (i=0;i<NUM_SOUNDS;++i){ if (!(SDL_LoadWAV(file[i],&wave,&data,&dlen))){ return; } SDL_BuildAudioCVT(&cvt[i],wave.format,wave.channels,wave.freq,AUDIO_S16,2,22050); cvt[i].buf=malloc(dlen*cvt[i].len_mult); memcpy(cvt[i].buf,data,dlen); cvt[i].len=dlen; SDL_ConvertAudio(&cvt[i]); s[i].data=cvt[i].buf; s[i].dlen=cvt[i].len_cvt; SDL_FreeWAV(data); } }
void AudioMixer::playACMSound(std::string filename) { auto acm = ResourceManager::acmFileType(filename); if (!acm) return; Logger::debug("AudioMixer") << "playing: " << acm->filename() << std::endl; Mix_Chunk *chunk = NULL; auto it = _sfx.find(acm->filename()); if (it != _sfx.end()) { chunk=it->second; } if (!chunk) { acm->init(); auto samples = acm->samples(); uint8_t *memory = new uint8_t [samples * 2]; auto cnt = acm->readSamples((short*)memory, samples)*2; SDL_AudioCVT cvt; SDL_BuildAudioCVT(&cvt, AUDIO_S16LSB, 1, 22050, AUDIO_S16LSB, 2, 22050); //convert from mono to stereo cvt.buf = (Uint8*)malloc(cnt*cvt.len_mult); memcpy(cvt.buf, (uint8_t*)memory, cnt); cvt.len = cnt; SDL_ConvertAudio(&cvt); // free old buffer delete [] memory; // make SDL_mixer chunk chunk = Mix_QuickLoad_RAW(cvt.buf, cvt.len*cvt.len_ratio); if (_sfx.size() > 100) // TODO: make this configurable { Mix_FreeChunk(_sfx.begin()->second); _sfx.erase(_sfx.begin()); } _sfx.insert(std::pair<std::string, Mix_Chunk*>(acm->filename(), chunk)); } Mix_PlayChannel(-1, chunk, 0); }
void Sound::init() { if(mSampleData != NULL) deinit(); if(mPath.empty()) return; //load wav file via SDL SDL_AudioSpec wave; Uint8 * data = NULL; Uint32 dlen = 0; if (SDL_LoadWAV(mPath.c_str(), &wave, &data, &dlen) == NULL) { LOG(LogError) << "Error loading sound \"" << mPath << "\"!\n" << " " << SDL_GetError(); return; } //build conversion buffer SDL_AudioCVT cvt; SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 44100); //copy data to conversion buffer cvt.len = dlen; cvt.buf = new Uint8[cvt.len * cvt.len_mult]; memcpy(cvt.buf, data, dlen); //convert buffer to stereo, 16bit, 44.1kHz if (SDL_ConvertAudio(&cvt) < 0) { LOG(LogError) << "Error converting sound \"" << mPath << "\" to 44.1kHz, 16bit, stereo format!\n" << " " << SDL_GetError(); delete[] cvt.buf; } else { //worked. set up member data SDL_LockAudio(); mSampleData = cvt.buf; mSampleLength = cvt.len_cvt; mSamplePos = 0; mSampleFormat.channels = 2; mSampleFormat.freq = 44100; mSampleFormat.format = AUDIO_S16; SDL_UnlockAudio(); } //free wav data now SDL_FreeWAV(data); }
static FluidSynthMidiSong *fluidsynth_loadsong_common(int (*function)(FluidSynthMidiSong*, void*), void *data) { FluidSynthMidiSong *song; fluid_settings_t *settings = NULL; if (!Mix_Init(MIX_INIT_FLUIDSYNTH)) { return NULL; } if ((song = SDL_malloc(sizeof(FluidSynthMidiSong)))) { SDL_memset(song, 0, sizeof(FluidSynthMidiSong)); if (SDL_BuildAudioCVT(&song->convert, AUDIO_S16, 2, freq, format, channels, freq) >= 0) { if ((settings = fluidsynth.new_fluid_settings())) { fluidsynth.fluid_settings_setnum(settings, "synth.sample-rate", (double) freq); if ((song->synth = fluidsynth.new_fluid_synth(settings))) { if (Mix_EachSoundFont(fluidsynth_load_soundfont, (void*) song->synth)) { if ((song->player = fluidsynth.new_fluid_player(song->synth))) { if (function(song, data)) return song; fluidsynth.delete_fluid_player(song->player); } else { Mix_SetError("Failed to create FluidSynth player"); } } fluidsynth.delete_fluid_synth(song->synth); } else { Mix_SetError("Failed to create FluidSynth synthesizer"); } fluidsynth.delete_fluid_settings(settings); } else { Mix_SetError("Failed to create FluidSynth settings"); } } else { Mix_SetError("Failed to set up audio conversion"); } SDL_free(song); } else { Mix_SetError("Insufficient memory for song"); } return NULL; }
/** ** Convert RAW sound data to 44100 hz, Stereo, 16 bits per channel ** ** @param src Source buffer ** @param dest Destination buffer ** @param frequency Frequency of source ** @param chansize Bitrate in bytes per channel of source ** @param channels Number of channels of source ** @param bytes Number of compressed bytes to read ** ** @return Number of bytes written in 'dest' */ static int ConvertToStereo32(const char *src, char *dest, int frequency, int chansize, int channels, int bytes) { SDL_AudioCVT acvt; Uint16 format; if (chansize == 1) { format = AUDIO_U8; } else { format = AUDIO_S16SYS; } SDL_BuildAudioCVT(&acvt, format, channels, frequency, AUDIO_S16SYS, 2, 44100); acvt.buf = (Uint8 *)dest; memcpy(dest, src, bytes); acvt.len = bytes; SDL_ConvertAudio(&acvt); return acvt.len_mult * bytes; }