void buffer_load(char* filename, ALint* buffer) { SF_INFO file_infos; SNDFILE* file = sf_open(filename, SFM_READ, &file_infos); if(!file) printf("Unable to load the soundfile %s ! Ensure to be in the same directory as the ttymetronome binary.\n", filename); ALsizei sample_number = (ALsizei)(file_infos.channels * file_infos.frames); ALsizei samplerate = (ALsizei)(file_infos.samplerate); ALshort samples[sample_number]; sf_read_short(file,samples,sample_number); sf_close(file); ALenum type; switch(file_infos.channels) { case 1: type = AL_FORMAT_MONO16; break; case 2: type = AL_FORMAT_STEREO16; break; } alGenBuffers(1,buffer); alBufferData(*buffer,type,samples,sample_number * sizeof(ALushort), samplerate); if(alGetError()) printf("Internal OpenAL error !\n"); return; }
bool ALAudio::load_sndfile(std::string const& filename, EASYRPG_SHARED_PTR<buffer> const& buf) { SF_INFO info; EASYRPG_SHARED_PTR<SNDFILE> file(sf_open(filename.c_str(), SFM_READ, &info), sf_close); if(! file) { return false; } // load data std::vector<int16_t> data; EASYRPG_ARRAY<int16_t, 4096> read_buf; size_t read_size = 0; while((read_size = sf_read_short(file.get(), read_buf.data(), read_buf.size())) != 0) { data.insert(data.end(), read_buf.begin(), read_buf.begin() + read_size); } // channel check ALsizei const channels = (info.channels == 1)? AL_FORMAT_MONO16: (info.channels == 2)? AL_FORMAT_STEREO16: AL_INVALID_VALUE; if(channels == AL_INVALID_VALUE) { return false; } alBufferData(buf->get(), channels, &data.front(), data.size() * sizeof(int16_t), info.samplerate); return true; }
//////////////////////////////////////////////////////////// /// Read samples from the loaded sound //////////////////////////////////////////////////////////// std::size_t SoundFileDefault::Read(Int16* Data, std::size_t NbSamples) { if (myFile && Data && NbSamples) return static_cast<std::size_t>(sf_read_short(myFile, Data, NbSamples)); else return 0; }
static void opensoundsys_play (int argc, char *argv []) { static short buffer [BUFFER_LEN] ; SNDFILE *sndfile ; SF_INFO sfinfo ; int k, audio_device, readcount, writecount, subformat ; for (k = 1 ; k < argc ; k++) { memset (&sfinfo, 0, sizeof (sfinfo)) ; printf ("Playing %s\n", argv [k]) ; if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo))) { puts (sf_strerror (NULL)) ; continue ; } ; if (sfinfo.channels < 1 || sfinfo.channels > 2) { printf ("Error : channels = %d.\n", sfinfo.channels) ; continue ; } ; audio_device = opensoundsys_open_device (sfinfo.channels, sfinfo.samplerate) ; subformat = sfinfo.format & SF_FORMAT_SUBMASK ; if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE) { static float float_buffer [BUFFER_LEN] ; double scale ; int m ; sf_command (sndfile, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ; if (scale < 1e-10) scale = 1.0 ; else scale = 32700.0 / scale ; while ((readcount = sf_read_float (sndfile, float_buffer, BUFFER_LEN))) { for (m = 0 ; m < readcount ; m++) buffer [m] = scale * float_buffer [m] ; writecount = write (audio_device, buffer, readcount * sizeof (short)) ; } ; } else { while ((readcount = sf_read_short (sndfile, buffer, BUFFER_LEN))) writecount = write (audio_device, buffer, readcount * sizeof (short)) ; } ; if (ioctl (audio_device, SNDCTL_DSP_POST, 0) == -1) perror ("ioctl (SNDCTL_DSP_POST) ") ; if (ioctl (audio_device, SNDCTL_DSP_SYNC, 0) == -1) perror ("ioctl (SNDCTL_DSP_SYNC) ") ; close (audio_device) ; sf_close (sndfile) ; } ; return ; } /* opensoundsys_play */
static void win32_play_data (Win32_Audio_Data *audio_data) { int thisread, readcount ; /* fill a buffer if there is more data and we can read it sucessfully */ readcount = (audio_data->remaining > audio_data->bufferlen) ? audio_data->bufferlen : (int) audio_data->remaining ; thisread = (int) sf_read_short (audio_data->sndfile, (short *) (audio_data->whdr [audio_data->current].lpData), readcount) ; audio_data->remaining -= thisread ; if (thisread > 0) { /* Fix buffer length if this is only a partial block. */ if (thisread < audio_data->bufferlen) audio_data->whdr [audio_data->current].dwBufferLength = thisread * sizeof (short) ; /* Queue the WAVEHDR */ waveOutWrite (audio_data->hwave, (LPWAVEHDR) &(audio_data->whdr [audio_data->current]), sizeof (WAVEHDR)) ; /* count another buffer in use */ EnterCriticalSection (&audio_data->mutex) ; audio_data->BuffersInUse ++ ; LeaveCriticalSection (&audio_data->mutex) ; /* use the other buffer next time */ audio_data->current = (audio_data->current + 1) % 2 ; } ; return ; } /* win32_play_data */
int main (int argc, char *argv[]) { SNDFILE *file ; SF_INFO sfinfo ; int k, count, max = 0, total = 0 ; if (argc < 2) { printf ("Expecting input file name.\n") ; return 0 ; } ; if (! (file = sf_open_read (argv [1], &sfinfo))) { printf ("sf_open_read failed with error : ") ; sf_perror (NULL) ; exit (1) ; } ; while ((count = sf_read_short (file, buffer, BUFFER_SIZE))) { for (k = 0 ; k < count ; k++) if (abs (buffer [k]) > max) max = abs (buffer [k]) ; total += count ; } ; printf ("Total : %d\n", total) ; printf ("Maximun value : %d\n", max) ; sf_close (file) ; return 0 ; } /* main */
int prSFRead(struct VMGlobals *g, int numArgsPushed) { PyrSlot *a, *b; a = g->sp - 1; b = g->sp; SNDFILE *file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]); if (!isKindOfSlot(b, class_rawarray)) return errWrongType; switch (slotRawObject(b)->obj_format) { case obj_int16 : slotRawObject(b)->size = sf_read_short(file, (short*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_int32 : slotRawObject(b)->size = sf_read_int(file, (int*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_float : slotRawObject(b)->size = sf_read_float(file, (float*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_double : slotRawObject(b)->size = sf_read_double(file, (double*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; default: error("sample format not supported.\n"); return errFailed; } return errNone; }
int CWAV::ReadDataChunk(BYTE* pBuf, DWORD dwNumBytes) { ASSERT(m_pSndFile); return (int)sf_read_short( m_pSndFile, (PSHORT)pBuf, dwNumBytes / sizeof( SHORT ) ) * sizeof( SHORT ); }
static void win32_play_data (Win32_Audio_Data *audio_data) { int thisread, readcount ; readcount = (audio_data->remaining > audio_data->bufferlen) ? audio_data->bufferlen : (int) audio_data->remaining ; thisread = (int) sf_read_short (audio_data->sndfile, (short *) (audio_data->whdr [audio_data->current].lpData), readcount) ; audio_data->remaining -= thisread ; if (thisread > 0) { /* Fix buffer length is only a partial block. */ if (thisread * sizeof (short) < audio_data->bufferlen) audio_data->whdr [audio_data->current].dwBufferLength = thisread * sizeof (short) ; /* Queue the WAVEHDR */ waveOutWrite (audio_data->hwave, (LPWAVEHDR) &(audio_data->whdr [audio_data->current]), sizeof (WAVEHDR)) ; } else { /* Stop playback */ waveOutPause (audio_data->hwave) ; SetEvent (audio_data->Event) ; } ; audio_data->current = (audio_data->current + 1) % 2 ; } /* win32_play_data */
f_cnt_t SampleBuffer::decodeSampleSF( const char * _f, int_sample_t * & _buf, ch_cnt_t & _channels, sample_rate_t & _samplerate ) { SNDFILE * snd_file; SF_INFO sf_info; f_cnt_t frames = 0; bool sf_rr = false; sample_t * fbuf = 0; if( ( snd_file = sf_open( _f, SFM_READ, &sf_info ) ) != NULL ) { frames = sf_info.frames; // check if float if ( (sf_info.format & SF_FORMAT_SUBMASK) == SF_FORMAT_FLOAT ) // if yes, use float format for buffer { fbuf = new sample_t[sf_info.channels * frames]; sf_rr = sf_read_float( snd_file, fbuf, sf_info.channels * frames ); } else // otherwise, use int { _buf = new int_sample_t[sf_info.channels * frames]; sf_rr = sf_read_short( snd_file, _buf, sf_info.channels * frames ); } if( sf_rr < sf_info.channels * frames ) { #ifdef DEBUG_LMMS printf( "SampleBuffer::decodeSampleSF(): could not read" " sample %s: %s\n", _f, sf_strerror( NULL ) ); #endif } _channels = sf_info.channels; _samplerate = sf_info.samplerate; sf_close( snd_file ); } else { #ifdef DEBUG_LMMS printf( "SampleBuffer::decodeSampleSF(): could not load " "sample %s: %s\n", _f, sf_strerror( NULL ) ); #endif } //write down either directly or convert i->f depending on file type if ( frames > 0 && fbuf != NULL ) { directFloatWrite ( fbuf, frames, _channels); } else if ( frames > 0 && _buf != NULL ) { convertIntToFloat ( _buf, frames, _channels); } return frames; }
int32 SndfileDecoder::Decode(uint8* buffer, int32 max_length) { if (!sndfile) { return 0; } return sf_read_short(sndfile, (int16*) buffer, max_length / 2) * 2; }
// TODO: Add streaming support. bool SoundCtor(JSContext *ctx, unsigned argc, JS::Value *vp){ JS::CallArgs args = CallArgsFromVp(argc, vp); if(!Turbo::CheckForSingleArg(ctx, args, Turbo::String, __func__)) return false; struct Turbo::JSStringHolder<> file(ctx, JS_EncodeString(ctx, args[0].toString())); const std::string full_path = std::string(TS_GetContextEnvironment(ctx)->directories->sound) + file.string; if(!t5::IsFile(full_path)){ Turbo::SetError(ctx, std::string(BRACKNAME " SoundCtor Error no such file ") + file.string); return false; } SF_INFO info; SNDFILE *sound_file = sf_open(full_path.c_str(), SFM_READ, &info); //sf_command(sound_file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE); if(!sound_file){ Turbo::SetError(ctx, std::string(BRACKNAME " SoundCtor Error could not open file ") + file.string); return false; } int iters = 0; Sound *sound = nullptr; if(player.supportsFloat32()){ float buffer[0x8000]; sound = new Sound(player.load((float *)nullptr, 0, info.channels, info.samplerate, info.frames)); while(unsigned long this_read = sf_read_float(sound_file, buffer, 0x10000)){ player.addToSound(sound, buffer, SamplesToBytes(this_read)); iters++; } } else if(player.supportsInt16()){ short buffer[0x10000]; sound = new Sound(player.load((short *)nullptr, 0, info.channels, info.samplerate, info.frames)); while(unsigned long this_read = sf_read_short(sound_file, buffer, 0x10000)){ player.addToSound(sound, buffer, SamplesToBytes(this_read)); iters++; } } else{ puts(BRACKNAME " Error bad player on this platform"); } printf(BRACKNAME " SoundCtor Info loaded file %s in %i iterations\n", file.string, iters); sf_close(sound_file); args.rval().set(OBJECT_TO_JSVAL(sound_proto.wrap(ctx, sound))); return true; }
ALuint Lecture::LoadSound(const std::string& Filename) { // Ouverture du fichier audio avec libsndfile SF_INFO FileInfos; SNDFILE* File = sf_open(Filename.c_str(), SFM_READ, &FileInfos); if (!File) { qDebug() << "Impossible d'ouvrir le fichier audio"; return 0; } // Lecture du nombre d'échantillons et du taux d'échantillonnage (nombre d'échantillons à lire par seconde) ALsizei NbSamples = static_cast<ALsizei>(FileInfos.channels * FileInfos.frames); ALsizei SampleRate = static_cast<ALsizei>(FileInfos.samplerate); // Lecture des échantillons audio au format entier 16 bits signé (le plus commun) std::vector<ALshort> Samples(NbSamples); if (sf_read_short(File, &Samples[0], NbSamples) < NbSamples) { qDebug() << "Impossible de lire les échantillons stockés dans le fichier audio"; return 0; } // Fermeture du fichier sf_close(File); // Détermination du format en fonction du nombre de canaux ALenum Format; switch (FileInfos.channels) { case 1 : Format = AL_FORMAT_MONO16; break; case 2 : Format = AL_FORMAT_STEREO16; break; default : qDebug() << "Format audio non supporté (plus de 2 canaux)"; return 0; } // Création du tampon OpenAL ALuint Buffer; alGenBuffers(1, &Buffer); // Remplissage avec les échantillons lus alBufferData(Buffer, Format, &Samples[0], NbSamples * sizeof(ALushort), SampleRate); // Vérification des erreurs if (alGetError() != AL_NO_ERROR) { qDebug() << "Impossible de remplir le tampon OpenAL avec les échantillons du fichier audio" ; return 0; } return Buffer; }
bool M_loadSound(const char * filename, void * data) { SF_VIRTUAL_IO io; io.get_filelen = &M_SFGetFileLen; io.seek = &M_SFSeek; io.read = &M_SFRead; io.write = &M_SFWrite; io.tell = &M_SFTell; // open file SF_INFO infos; MFile* File = M_fopen(filename, "rb"); SNDFILE * file = sf_open_virtual(&io, SFM_READ, &infos, File); if(! file){ M_fclose(File); printf("ERROR Load Sound : unable to read %s file\n", filename); return false; } int nbSamples = infos.channels * (int)infos.frames; int sampleRate = infos.samplerate; M_SOUND_FORMAT format; switch(infos.channels) { case 1 : format = M_SOUND_FORMAT_MONO16; break; case 2 : format = M_SOUND_FORMAT_STEREO16; break; default : printf("ERROR Load Sound : non supported format\n"); M_fclose(File); return false; } MSound * sound = (MSound *)data; unsigned int size = nbSamples*2; sound->create(format, size, (unsigned int)sampleRate); // 16 bits file reading if(sf_read_short(file, (short*)sound->getData(), nbSamples) < nbSamples) { printf("ERROR Load Sound : unable to read samples\n"); M_fclose(File); return false; } sf_close(file); M_fclose(File); return true; }
static void mbrpipe_play_icon(char *icon) { #if HAVE_SNDFILE int subformat; sf_count_t items; sf_count_t readcount; SNDFILE *sf; SF_INFO sfinfo; char filename[256]; sprintf(filename, "%s/%s",MbrpipeSoundIconFolder,icon); log_msg(OTTS_LOG_DEBUG, MODULE_NAME": Playing |%s|", filename); memset(&sfinfo, 0, sizeof(sfinfo)); sf = sf_open(filename, SFM_READ, &sfinfo); if (!sf) return; subformat = sfinfo.format & SF_FORMAT_SUBMASK; items = sfinfo.channels * sfinfo.frames; if (sfinfo.channels < 1 || sfinfo.channels > 2) { log_msg(OTTS_LOG_ERR, MODULE_NAME": channels = %d.\n", sfinfo.channels); goto cleanup1; } if (sfinfo.frames > 0x7FFFFFFF) { log_msg(OTTS_LOG_ERR, MODULE_NAME": Unknown number of frames."); goto cleanup1; } if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE) { /* Set scaling for float to integer conversion. */ sf_command(sf, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE); } AudioTrack track; track.num_samples = sfinfo.frames; track.num_channels = sfinfo.channels; track.sample_rate = sfinfo.samplerate; track.bits = 16; track.samples = g_malloc(items * sizeof(short)); readcount = sf_read_short(sf, (short *)track.samples, items); if (readcount > 0) { track.num_samples = readcount / sfinfo.channels; opentts_audio_set_volume(module_audio_id, mbrpipe_volume); int ret = opentts_audio_play(module_audio_id, track, SPD_AUDIO_LE); if (ret < 0) { log_msg(OTTS_LOG_ERR, MODULE_NAME ": Can't play track for unknown reason."); goto cleanup2; } } cleanup2: g_free(track.samples); cleanup1: sf_close(sf); #endif }
// --- Read --- MediumFrame* SndFileHandler::m_read() { current_ts += step; f->len = sf_read_short(s_file, f->samples, AUDIO_BUFFER_SIZE * file_info.channels); f->ts = current_ts; if (f->len == 0) return NULL; return f; }
/* read <size> samples into <destination>, and return the number of samples actually read. A sample is a single float representing a sample on one channel of the audio. In the case of a monaural file then size/2 samples are read from the mono file, and they are doubled into stereo. */ unsigned SoundSourceSndFile::read(unsigned long size, const SAMPLE * destination) { SAMPLE * dest = (SAMPLE *)destination; if (filelength > 0) { if (channels==2) { unsigned long no = sf_read_short(fh, dest, size); // rryan 2/2009 This code used to lie and say we read // 'size' samples no matter what. I left this array // zeroing code here in case the Reader doesn't check // against this. for (unsigned long i=no; i<size; ++i) dest[i] = 0; return no; } else if(channels==1) { // We are not dealing with a stereo file. Read fewer // samples than requested and double them because we // pretend to every reader that all files are in stereo. int readNo = sf_read_short(fh, dest, size/2); // dest has enough capacity for (readNo * 2) samples SampleUtil::doubleMonoToDualMono(dest, readNo); // We doubled the readNo bytes we read into stereo. return readNo * 2; } else { // We do not support music with more than 2 channels. return 0; } } // The file has errors or is not open. Tell the truth and return 0. qDebug() << "The file has errors or is not open: " << getFilename(); return 0; }
bool StreamTrack::stream(ALuint buffer) { BOOST_ASSERT(m_audioEngine->getSettings().stream_buffer_size >= m_sfInfo.channels - 1); #ifdef AUDIO_OPENAL_FLOAT std::vector<ALfloat> pcm(m_audioEngine->getSettings().stream_buffer_size); #else std::vector<ALshort> pcm(m_audioEngine->getSettings().stream_buffer_size); #endif size_t size = 0; // SBS - C + 1 is important to avoid endless loops if the buffer size isn't a multiple of the channels while(size < pcm.size() - m_sfInfo.channels + 1) { // we need to read a multiple of sf_info.channels here const size_t samplesToRead = (m_audioEngine->getSettings().stream_buffer_size - size) / m_sfInfo.channels * m_sfInfo.channels; #ifdef AUDIO_OPENAL_FLOAT const sf_count_t samplesRead = sf_read_float(m_sndFile, pcm.data() + size, samplesToRead); #else const sf_count_t samplesRead = sf_read_short(m_sndFile, pcm.data() + size, samplesToRead); #endif if(samplesRead > 0) { BOOST_ASSERT(static_cast<std::make_unsigned<sf_count_t>::type>(samplesRead) <= std::numeric_limits<size_t>::max()); size += static_cast<size_t>(samplesRead); continue; } int error = sf_error(m_sndFile); if(error != SF_ERR_NO_ERROR) { logSndfileError(error); return false; } if(m_streamType == StreamType::Background) { sf_seek(m_sndFile, 0, SEEK_SET); } else { break; // Stream is ending - do nothing. } } if(size == 0) return false; alBufferData(buffer, m_format, pcm.data(), static_cast<ALsizei>(size * sizeof(pcm[0])), m_rate); DEBUG_CHECK_AL_ERROR(); return true; }
ssize_t ad_read_sndfile_short(WfDecoder* d, WfBuf16* buf) { SndfileDecoder* sf = (SndfileDecoder*)d->d; switch(d->info.bit_depth){ case 8: case 16: { if(d->info.channels == 1){ return sf_readf_short(sf->sffile, buf->buf[0], buf->size); }else{ short* data = g_malloc0(d->info.channels * buf->size * sizeof(short)); ssize_t r = sf_read_short(sf->sffile, data, d->info.channels * buf->size); int i, f; for(i=0,f=0;i<r;i+=d->info.channels,f++){ int c; for(c=0;c<d->info.channels;c++){ buf->buf[c][f] = data[i]; } } g_free(data); return f; } } case 24: { int* data = g_malloc0(d->info.channels * buf->size * sizeof(int)); ssize_t r = sf_read_int(sf->sffile, data, d->info.channels * buf->size); int i, f; for(i=0,f=0;i<r;i+=d->info.channels,f++){ int c; for(c=0;c<d->info.channels;c++){ buf->buf[c][f] = data[i] >> 16; } } g_free(data); return f; } case 32: { float* data = g_malloc0(d->info.channels * buf->size * sizeof(float)); ssize_t r = sf_read_float(sf->sffile, data, d->info.channels * buf->size); int i, f; for(i=0,f=0;i<r;i+=d->info.channels,f++){ int c; for(c=0;c<d->info.channels;c++){ buf->buf[c][f] = AD_FLOAT_TO_SHORT(data[i]); } } g_free(data); return r; } #ifdef DEBUG default: dbg(0, "!!! unhandled bit depth: %i", d->info.bit_depth); #endif } return -1; }
int fluid_sample_import_file(char * filepath, short *data, long seekPos, long nbFramesToLoad, long *nbFramesLoaded, int *samplerate, int *nbchannels) { int err; int bytesPerSample; int bytesPerFrame; unsigned long fileBytes; long nbSamplesRead; short needsTwoComplementing; SNDFILE * infile; SF_INFO sfinfo; long samplesToRead; // open file, read info infile = sf_open_read (filepath, &sfinfo) ; if (!infile) { return FLUIDXTRAERR_OPENREADFILE; } bytesPerSample = sfinfo.pcmbitwidth/8; if (bytesPerSample != 2) { err = FLUIDXTRAERR_BADFILEFORMAT; goto bail; } bytesPerFrame = sfinfo.channels*bytesPerSample; fileBytes = (unsigned long)sfinfo.samples*bytesPerFrame; needsTwoComplementing = (sfinfo.format & SF_FORMAT_AIFF) && (bytesPerSample == 1); if (seekPos > 0) { off_t res = sf_seek(infile, seekPos, SEEK_SET); if (res < 0) { err = FLUIDXTRAERR_SEEKFILE; *nbFramesLoaded = 0; goto bail; } } samplesToRead = (nbFramesToLoad >= 0 ? nbFramesToLoad : sfinfo.samples)*sfinfo.channels; nbSamplesRead = sf_read_short (infile, data, samplesToRead); *nbFramesLoaded = nbSamplesRead/sfinfo.channels; *samplerate = sfinfo.samplerate; *nbchannels = sfinfo.channels; err = 0; bail: if (infile) sf_close (infile); return err; }
static void sndio_play (int argc, char *argv []) { struct sio_hdl *hdl ; struct sio_par par ; short buffer [BUFFER_LEN] ; SNDFILE *sndfile ; SF_INFO sfinfo ; int k, readcount ; for (k = 1 ; k < argc ; k++) { printf ("Playing %s\n", argv [k]) ; if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo))) { puts (sf_strerror (NULL)) ; continue ; } ; if (sfinfo.channels < 1 || sfinfo.channels > 2) { printf ("Error : channels = %d.\n", sfinfo.channels) ; continue ; } ; if ((hdl = sio_open (NULL, SIO_PLAY, 0)) == NULL) { fprintf (stderr, "open sndio device failed") ; return ; } ; sio_initpar (&par) ; par.rate = sfinfo.samplerate ; par.pchan = sfinfo.channels ; par.bits = 16 ; par.sig = 1 ; par.le = SIO_LE_NATIVE ; if (! sio_setpar (hdl, &par) || ! sio_getpar (hdl, &par)) { fprintf (stderr, "set sndio params failed") ; return ; } ; if (! sio_start (hdl)) { fprintf (stderr, "sndio start failed") ; return ; } ; while ((readcount = sf_read_short (sndfile, buffer, BUFFER_LEN))) sio_write (hdl, buffer, readcount * sizeof (short)) ; sio_close (hdl) ; } ; return ; } /* sndio_play */
SoundHandle AudioDevice::createSound(const std::string &name) { // Perform cleanup before creating new sounds audioCleanup(); auto itr = m_audioFiles.find(name); if(itr != m_audioFiles.end()) { // Check if data hasn't been loaded for this file previously if(!alIsBuffer(itr->second.buffer) || itr->second.buffer == 0) { // Open file and save initial data SF_INFO fileInfo; SNDFILE *file = sf_open(itr->second.fileName.c_str(), SFM_READ, &fileInfo); if(file == NULL) { JL_WARNING_LOG("Could not open audio file '%s'", itr->second.fileName.c_str()); return SoundHandle(); } // Create new buffer alGenBuffers(1, &itr->second.buffer); // Read whole file int sampleCount = fileInfo.frames * fileInfo.channels; std::vector<ALshort> fileData(sampleCount); sf_read_short(file, &fileData[0], sampleCount); alBufferData( itr->second.buffer, AudioDevice::getFormatFromChannels(fileInfo.channels), &fileData[0], sampleCount*sizeof(ALushort), fileInfo.samplerate); sf_close(file); } // Create new audio source m_sounds.push_back( SoundHandle(new AudioChunk(itr->second.buffer, itr->second.fileName))); return m_sounds.back(); } else { JL_WARNING_LOG("Couldn't find any sound by the name '%s'", name.c_str()); return SoundHandle(nullptr); } }
size_t sndfile_read(struct audio_file *fd, int16_t *buf, size_t len) { SNDFILE *hnd = fd->drv_data; sf_count_t ret, frame; ret = sf_read_short(hnd, buf, len); /* Seek zero frames to obtain the current position */ frame = sf_seek(hnd, 0, SEEK_CUR); fd->time_cur = frame / fd->srate; return (ret); }
/** * Try to read @a sampnum samples and returns actual sample num recorded. * * @param buf [out] samples obtained in this function * @param sampnum [in] wanted number of samples to be read * * @return actural number of read samples, -1 if EOF, -2 if error. */ int adin_sndfile_read(SP16 *buf, int sampnum) { int cnt; cnt = sf_read_short(sp, buf, sampnum); if (cnt == 0) { /* EOF */ return -1; } else if (cnt < 0) { /* error */ sf_perror(sp); sf_close(sp); return -2; /* error */ } return cnt; }
/* Reques for writing length data */ static void sdlLibsndfileCb(void *userdata, Uint8 *stream, int len) { /* Just empty buffer for no reason.. fun yea */ memset( stream, 0x00, len); /* Read with libsndfile */ #if SDL_MAJOR_VERSION == 2 m_iReadcount = sf_read_float(m_SInfile, (float *)stream, len / 4); #else m_iReadcount = sf_read_short(m_SInfile, (short int *)stream, len / 2); #endif if( m_iReadcount <= 0 ) { l_iLoop = 1; } }
void SoundManager::SoundSource::loadFromFile(const std::string& filename) { fileInfo.format = 0; file = sf_open(filename.c_str(), SFM_READ, &fileInfo); if (file) { size_t numRead = 0; std::array<int16_t, 4096> readBuffer; while ((numRead = sf_read_short(file, readBuffer.data(), readBuffer.size())) != 0) { data.insert(data.end(), readBuffer.begin(), readBuffer.begin() + numRead); } } else { std::cerr << "Error opening sound file \"" << filename << "\": " << sf_strerror(file) << std::endl; } }
/** * Process PCM audio from a libsndfile file. FIXME: looks a lot like * decode_pcm! Also needs stereo support (as does decode_pcm). */ static int decode_sndfile(sphinx_wave2feat_t *wtf) { size_t nsamp; int32 nfr, nchans, whichchan; int nfloat, n; nchans = cmd_ln_int32_r(wtf->config, "-nchans"); whichchan = cmd_ln_int32_r(wtf->config, "-whichchan"); fe_start_utt(wtf->fe); nfloat = 0; while ((nsamp = sf_read_short(wtf->insfh, wtf->audio, wtf->blocksize)) != 0) { int16 const *inspeech; size_t nvec; /* Mix or pick channels. */ if (nchans > 1) nsamp = mixnpick_channels(wtf->audio, nsamp, nchans, whichchan); inspeech = wtf->audio; nvec = wtf->featsize; /* Consume all samples. */ while (nsamp) { nfr = nvec; fe_process_frames(wtf->fe, &inspeech, &nsamp, wtf->feat, &nfr, NULL); if (nfr) { if ((n = (*wtf->ot->output_frames)(wtf, wtf->feat, nfr)) < 0) return -1; nfloat += n; } } inspeech = wtf->audio; } /* Now process any leftover audio frames. */ fe_end_utt(wtf->fe, wtf->feat[0], &nfr); if (nfr) { if ((n = (*wtf->ot->output_frames)(wtf, wtf->feat, nfr)) < 0) return -1; nfloat += n; } sf_close(wtf->insfh); wtf->insfh = NULL; return nfloat; }
void test_read_short_or_die (SNDFILE *file, int pass, short *test, sf_count_t items, int line_num) { sf_count_t count ; if ((count = sf_read_short (file, test, items)) != items) { printf ("\n\nLine %d", line_num) ; if (pass > 0) printf (" (pass %d)", pass) ; printf (" : sf_read_short failed with short read (%ld => %ld).\n", SF_COUNT_TO_LONG (items), SF_COUNT_TO_LONG (count)) ; fflush (stdout) ; puts (sf_strerror (file)) ; exit (1) ; } ; return ; } /* test_read_short */
int cf_sndfile_read(CODECFILTER_USERDATA_T inst, char * buf, int len) { struct codecfilter_sndfile_inst * obj = (struct codecfilter_sndfile_inst *) inst; struct roar_stream * s = ROAR_STREAM(obj->stream); int ret; if ( obj->opened ) { len /= obj->bytes; if ( obj->bytes == 2 ) { if ( (ret = sf_read_short(obj->state, (short*)buf, len)) == -1 ) return -1; } else if ( obj->bytes == 4 ) { if ( (ret = sf_read_int(obj->state, (int*)buf, len)) == -1 ) return -1; } else { errno = ENOSYS; return -1; } return ret * obj->bytes; } else { if ( (obj->state = sf_open_fd(s->fh, SFM_READ, &(obj->info), 0)) == NULL ) { ROAR_ERR("cf_sndfile_read(*): can not sf_open_fd(*)!"); return -1; } ROAR_WARN("cf_sndfile_read(*): obj->info={.format=0x%.8x, .samplerate=%i, .channels=%i}", obj->info.format, obj->info.samplerate, obj->info.channels); s->info.codec = ROAR_CODEC_DEFAULT; s->info.rate = obj->info.samplerate; s->info.channels = obj->info.channels; obj->bytes = 2; if ( (obj->info.format & SF_FORMAT_SUBMASK) == SF_FORMAT_PCM_24 || (obj->info.format & SF_FORMAT_SUBMASK) == SF_FORMAT_PCM_32 ) { obj->bytes = 4; } s->info.bits = obj->bytes * 8; obj->opened = 1; errno = EAGAIN; } return -1; }
int getsample(short *sample, int nb) { int r; if (source) { r = sf_read_short(inwav, sample, nb); if (r == 0) r = -1; /* this is the end */ } else { r = snd_pcm_readi(capture_handle, sample, nb/nbch); if (r <= 0) fprintf(stderr, "cannot read from interface (%s)\n", snd_strerror(r)); r=r*nbch; } return r; }