示例#1
0
文件: wav.c 项目: pdkelly/audiograph
int wav_read_samples(struct wav_file *wav, float *buff, int count)
{
    int samples_read, i, j;

    /* If the source is mono, then simply read directly into the output buffer */
    if(wav->file_info.channels == 1)
        return sf_readf_float(wav->file_handle, buff, count);

    /* Otherwise resize internal buffer to hold stereo samples if necessary... */
    if(wav->buff_size < count * wav->file_info.channels)
    {
        wav->buff_size = count * wav->file_info.channels;
        if( !(wav->raw_buff = realloc(wav->raw_buff, wav->buff_size * sizeof(float))))
            return -1;
    }

    /* ...and read samples for all channels interleaved, then convert to mono. */
    samples_read = sf_readf_float(wav->file_handle, wav->raw_buff, count);
    for(i = 0; i < samples_read; i++)
    {
        buff[i] = 0;
        for(j = 0; j < wav->file_info.channels; j++)
            buff[i] += wav->raw_buff[i*wav->file_info.channels+j];
        buff[i] /= wav->file_info.channels;
    }

    return samples_read;
}
示例#2
0
void file_buffer_worker(void *ctx)
{
    AudioFile::pimpl *fileImpl = (AudioFile::pimpl *)ctx;
    int writeBuffer = (fileImpl->currentBufIndex == 0) ? 1 : 0;
    sf_seek(fileImpl->sndfile, fileImpl->framesBuffered, SF_SEEK_SET);
    size_t read = sf_readf_float(fileImpl->sndfile, fileImpl->bufs[writeBuffer], FRAMES_PER_FILE_BUFFER);
    fileImpl->framesBuffered += read;
    if (read < FRAMES_PER_FILE_BUFFER)
    {
        if (fileImpl->looping)
        {
            sf_seek(fileImpl->sndfile, 0, SF_SEEK_SET);
            size_t samplesDidRead = read * fileImpl->sfInfo.channels;
            size_t framesToRead = (FRAMES_PER_FILE_BUFFER - read);
            sf_readf_float(fileImpl->sndfile, &(fileImpl->bufs[writeBuffer][samplesDidRead]), framesToRead);
            fileImpl->framesBuffered = framesToRead;
        }
        else
        {
            fileImpl->needsBuffer = false;
        }
    }
    
    fileImpl->isBuffering = false;
}
示例#3
0
static float *load_interleaved_samples(const wchar_t *filename, SF_INFO *sf_info){
  SNDFILE *sndfile          = sf_open(STRING_get_chars(filename),SFM_READ,sf_info);
  if(sndfile==NULL)
    return NULL;

  float   *ret              = talloc_atomic(sizeof(float) * sf_info->channels * sf_info->frames);
  int      allocated_frames = sf_info->frames;

  int total_read_frames     = sf_readf_float(sndfile, ret, sf_info->frames);

  if(total_read_frames==0)
    return NULL;

  while(true){
    float samples[1024*sf_info->channels];
    int read_now = sf_readf_float(sndfile, samples, 1024);
    if(read_now==0)
      break;

    if(total_read_frames + read_now > allocated_frames){
      allocated_frames = (total_read_frames+read_now) * 2;
      ret = talloc_realloc(ret, allocated_frames * sizeof(float) * sf_info->channels);
    }

    memcpy(ret + (total_read_frames*sf_info->channels), samples, sizeof(float)*1024*sf_info->channels);

    total_read_frames += read_now;
  }

  sf_close(sndfile);

  sf_info->frames = total_read_frames;
  return ret;
}
示例#4
0
/* if channels is -1, then all channels are read into buffer
 (interleaved).  buf should be big enough to hold them all */
nframes_t
Audio_File_SF::read ( sample_t *buf, int channel, nframes_t len )
{
    if ( len > 256 * 100 )
        WARNING( "warning: attempt to read an insane number of frames (%lu) from soundfile\n", (unsigned long)len );

//    printf( "len = %lu, channels = %d\n", len, _channels );

    lock();

    nframes_t rlen;

    if ( _channels == 1 || channel == -1 )
        rlen = sf_readf_float( _in, buf, len );
    else
    {
        sample_t *tmp = new sample_t[ len * _channels ];

        rlen = sf_readf_float( _in, tmp, len );

        /* extract the requested channel */
        for ( unsigned int i = channel; i < rlen * _channels; i += _channels )
            *(buf++) = tmp[ i ];

        delete[] tmp;
    }

    _current_read += rlen;

    unlock();

    return rlen;
}
示例#5
0
int SoundStream::updateState(double time, double dt){
   int status = PV_SUCCESS;
   assert(fileStream);
    
    // if (time >= nextSampleTime) {
    //     nextSampleTime += (1.0 / sampleRate);
       //Read 1 frame
       int numRead = sf_readf_float(fileStream, soundBuf, 1);
       //EOF
       if(numRead == 0){
          sf_seek(fileStream, 0, SEEK_SET);
          numRead = sf_readf_float(fileStream, soundBuf, 1);
          if(numRead == 0){
             fprintf(stderr, "SoundStream:: Fatal error, is the file empty?\n");
             exit(EXIT_FAILURE);
          }
          std::cout << "Rewinding sound file\n";
       }
       else if(numRead > 1){
          fprintf(stderr, "SoundStream:: Fatal error, numRead is bigger than 1\n");
          exit(EXIT_FAILURE);
       }
       for(int fi = 0; fi < getLayerLoc()->nf; fi++){
          soundData[fi] = soundBuf[fi];
       }
   // }
    
   return status;
}
示例#6
0
static void ra_sound_read_float(RA_SOUND *snd, RA_BUFFER *buf, sf_count_t frames) {
    static float temp[1024];
    int temp_len = 1024;
    float *data = (float*)buf->data;
    float mix_sum;

    // Get info struct
    SF_INFO *info;
    Data_Get_Struct(snd->info, SF_INFO, info);

    // Up/Downmix based on channel matching
    sf_count_t read = 0, r, amount;
    int i, k;
    if(buf->channels == info->channels) { // Simply read data without mix
        read = sf_readf_float(snd->snd, data, frames);
    } else if(buf->channels == 1) { // Downmix to mono
        sf_count_t max = temp_len / info->channels;
        int channels;

        while(read < frames) {
            // Calculate # of frames to read
            amount = frames - read;
            if(amount > max) amount = max;

            r = sf_readf_float(snd->snd, temp, amount);
            if(r == 0) break;

            // Mix channels together by averaging all channels and store to buffer
            for(i = 0; i < r; i++) {
                mix_sum = 0;
                for(k = 0; k < info->channels; k++) mix_sum += temp[i * info->channels + k];
                data[read] = mix_sum/info->channels;
                read++;
            }
        }
    } else if(info->channels == 1) { // Upmix from mono by copying channel
        while(read < frames) {
            // Calculate # of frames to read
            amount = frames - read;
            if(amount > temp_len) amount = temp_len;

            r = sf_readf_float(snd->snd, temp, amount);
            if(r == 0) break;

            // Write every frame channel times to the buffer
            for(i = 0; i < r; i++) {
                for(k = 0; k < buf->channels; k++) {
                    data[read * buf->channels + k] = temp[i];
                }
                read++;
            }
        }
    } else {
        rb_raise(eRubyAudioError, "unsupported mix from %d to %d", buf->channels, info->channels);
    }

    buf->real_size = read;
}
示例#7
0
void playbackThread(PaStream* stream, char* sampleBlock, SNDFILE* filePtr, bool* stopPlaybackThread, std::mutex* stopPlaybackThread_mutex, bool* playbackThreadFinishedPlaying, std::mutex* playbackThreadFinishedPlaying_mutex){
    PaError err;
    //uses mutex to be thread safe. stopPlaybackThread could change at any time
    playbackThreadFinishedPlaying_mutex->lock();
    *playbackThreadFinishedPlaying = false;
    playbackThreadFinishedPlaying_mutex->unlock();
    stopPlaybackThread_mutex->lock();
    *stopPlaybackThread = false;
    bool stop = *stopPlaybackThread;
    stopPlaybackThread_mutex->unlock();
    long frames = FRAMES_PER_BUFFER;
    memset(sampleBlock, 0, FRAMES_PER_BUFFER*NUM_CHANNELS*SAMPLE_SIZE);
    while (!stop && frames == FRAMES_PER_BUFFER) {
        frames = sf_readf_float(filePtr, (float*)sampleBlock, FRAMES_PER_BUFFER);
        
        err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
        if( err != paNoError ){
            printError("Error in worker thread:");
            printPaError(err);
        }

        stopPlaybackThread_mutex->lock();
        stop = *stopPlaybackThread;
        stopPlaybackThread_mutex->unlock();
    }
    playbackThreadFinishedPlaying_mutex->lock();
    *playbackThreadFinishedPlaying = true;
    playbackThreadFinishedPlaying_mutex->unlock();
    //printLog("* Worker ending!");
}
示例#8
0
void SoundFileStream::load( SNDFILE *sf, const SF_INFO &info, sf_count_t beg, sf_count_t dur )
{
  delete[] _data;

  _dataOffset = beg;
  _dataSize = dur;

  _data = new short [_dataSize * info.channels];
  sf_seek( sf, _dataOffset, SEEK_SET);

  if (info.format & SF_FORMAT_FLOAT || info.format & SF_FORMAT_DOUBLE)
  {
    // libsndfile reading float into short is broken for non-power-of-two channel counts
    int sampleCount = _dataSize * info.channels;
    float *tmp = new float [sampleCount];
    _dataSize = sf_readf_float( sf, tmp, _dataSize );
    for (int i = 0; i < sampleCount; ++i)
        _data[i] = std::max( -1.f, std::min( 1.f, tmp[i] ) ) * std::numeric_limits<short>::max();
    delete[] tmp;
  }
  else
  {
    _dataSize = sf_readf_short( sf, _data, _dataSize );
  }

  _ch = info.channels;
  _beg = _dataOffset;
  _dur = _dataSize;
}
示例#9
0
int sp_ftbl_loadfile(sp_data *sp, sp_ftbl **ft, const char *filename)
{
    *ft = malloc(sizeof(sp_ftbl));
    sp_ftbl *ftp = *ft;
    SF_INFO info;
    memset(&info, 0, sizeof(SF_INFO));
    info.format = 0;
    SNDFILE *snd = sf_open(filename, SFM_READ, &info);
    if(snd == NULL) {
        return SP_NOT_OK;
    }
    size_t size = info.frames * info.channels;

    ftp->tbl = malloc(sizeof(SPFLOAT) * (size + 1));

    sp_ftbl_init(sp, ftp, size);

#ifdef USE_DOUBLE
    sf_readf_double(snd, ftp->tbl, ftp->size);
#else
    sf_readf_float(snd, ftp->tbl, ftp->size);
#endif
    sf_close(snd);
    return SP_OK;
}
示例#10
0
/*!	Read in a soundfile.
	The Array returned is one dimensional. Multi-channel soundfiles return multi-component arrays.
	
	<luacode>
	local sf = audio.soundfile(LuaAV.findfile("gong.wav"))
	print(sf)							--> Array
	print(sf.components)				--> 2 (stereo)
	print(sf.dim[1])					--> 265776 (sample frames)
	print(sf.dim[1]/audio.samplerate)	--> 6.03 (seconds)
	</luacode>
		
	@param soundfile path (string)
	@ret Array containing the soundfile data
	@name M.read
*/
int lua_soundfile_read(lua_State * L) {
	const char * path = luaL_checkstring(L, 1);
	
	SNDFILE *sf;
	SF_INFO sfinfo;
	
	sf = sf_open(path, SFM_READ, &sfinfo);
	if (sf == NULL) luaL_error(L, "failed to open soundfile %s", path);
	
	// call Array constructor with appropriate format:
	lua_pushcfunction(L, Glue<al::ArrayWrapper>::create);
	lua_pushinteger(L, sfinfo.channels);	
	lua_pushinteger(L, AlloFloat32Ty);
	lua_createtable(L, 1, 0);
	lua_pushinteger(L, sfinfo.frames);
	lua_rawseti(L, -2, 1);
	lua_call(L, 3, 1);
	
	al::ArrayWrapper * a = Glue<al::ArrayWrapper>::checkto(L, -1);

	// copy data in:
	sf_readf_float(sf, (float *)a->data.ptr, sfinfo.frames);
	
	sf_close(sf);
	
	return 1;
}
示例#11
0
float* Util::loadSound(const std::string& fileName, int& size)
{
	SF_INFO soundInfo;
	SNDFILE* file = sf_open(fileName.c_str(), SFM_READ, &soundInfo);

	if(!file)
	{
		printf("Failed to open sound file");
		return 0;
	}



	sf_count_t frames = soundInfo.frames * soundInfo.channels;
	size = frames;

	float* data = new float[frames];

	sf_readf_float(file, data, frames);

	/*
	for(int i = 0; i < frames; i++)
	{

	}
	*/

	sf_close(file);

	return data;
}
static ssize_t
sa_sndfile_read( simpleaudio *sa, void *buf, size_t nframes )
{
    SNDFILE *s = (SNDFILE *)sa->backend_handle;
    int n;
    switch ( sa->format ) {
	case SA_SAMPLE_FORMAT_FLOAT:
		n = sf_readf_float(s, buf, nframes);
		break;
	case SA_SAMPLE_FORMAT_S16:
		n = sf_readf_short(s, buf, nframes);
		break;
	default:
		assert(0);
		break;
    }
    if ( n < 0 ) {
	fprintf(stderr, "sf_read: ");
	sf_perror(s);
	return -1;
    }

    if ( sa->rxnoise != 0.0 ) {
	int i;
	float *fbuf = buf;
	float f = sa->rxnoise * 2;
	for ( i=0; i<nframes; i++ )
	    fbuf[i] += (drand48() - 0.5) * f;
    }

    // fprintf(stderr, "sf_read: nframes=%ld n=%d\n", nframes, n);
    return n;
}
sf_count_t Processor::read_frames(size_t start){
    size_t count = m_bufsize;
    sf_count_t readCount = 0;
    if (!m_file || !m_channelCount) {
        std::cerr << "no file or no channel" << std::endl;
        return 0;
    }
    if ((long)start >= m_fileInfo.frames) {
        std::cerr << "end of file" << std::endl;
	    return 0;
    }
    if (long(start + m_bufsize) > m_fileInfo.frames) {
	    count = m_fileInfo.frames - start;
    }
    if (sf_seek(m_file, start, SEEK_SET) < 0) {
        std::cerr << "sf_seek failed" << std::endl;
	    exit(EXIT_FAILURE);
	}
    if ((readCount = sf_readf_float(m_file, m_buffer, count)) < 0) {
        std::cerr << "sf_readf_float failed" << std::endl;
	    exit(EXIT_FAILURE);
	}
    //std::cout << readCount << std::endl;
    return readCount;
}
示例#14
0
size_t SndFileDecoder::read(char *buffer, size_t bytes)
{
    short *out = (short*)buffer;
    size_t frames = bytes / SndInfo.channels / 2;
    size_t total = 0;

    // It seems libsndfile has a bug with converting float samples from Vorbis
    // to the 16-bit shorts we use, which causes some PCM samples to overflow
    // and wrap, creating static. So instead, read the samples as floats and
    // convert to short ourselves.
    // Use a loop to convert a handful of samples at a time, avoiding a heap
    // allocation for temporary storage. 64 at a time works, though maybe it
    // could be more.
    while(total < frames)
    {
        size_t todo = MIN<size_t>(frames-total, 64/SndInfo.channels);
        float tmp[64];

        size_t got = (size_t)sf_readf_float(SndFile, tmp, todo);
        if(got < todo) frames = total + got;

        for(size_t i = 0;i < got*SndInfo.channels;i++)
            *out++ = (short)xs_CRoundToInt(clamp(tmp[i] * 32767.f, -32768.f, 32767.f));
        total += got;
    }
    return total * SndInfo.channels * 2;
}
void
WavFileReader::getInterleavedFrames(size_t start, size_t count,
				    SampleBlock &results) const
{
    if (count == 0) return;
    results.clear();
    results.reserve(count * m_fileInfo.channels);

    QMutexLocker locker(&m_mutex);

    if (!m_file || !m_channelCount) {
        return;
    }

    if ((long)start >= m_fileInfo.frames) {
//        SVDEBUG << "WavFileReader::getInterleavedFrames: " << start
//                  << " > " << m_fileInfo.frames << endl;
	return;
    }

    if (long(start + count) > m_fileInfo.frames) {
	count = m_fileInfo.frames - start;
    }

    sf_count_t readCount = 0;

    if (start != m_lastStart || count != m_lastCount) {

	if (sf_seek(m_file, start, SEEK_SET) < 0) {
//            std::cerr << "sf_seek failed" << std::endl;
	    return;
	}
	
	if (count * m_fileInfo.channels > m_bufsiz) {
//	    std::cerr << "WavFileReader: Reallocating buffer for " << count
//		      << " frames, " << m_fileInfo.channels << " channels: "
//		      << m_bufsiz << " floats" << std::endl;
	    m_bufsiz = count * m_fileInfo.channels;
	    delete[] m_buffer;
	    m_buffer = new float[m_bufsiz];
	}
	
	if ((readCount = sf_readf_float(m_file, m_buffer, count)) < 0) {
//            std::cerr << "sf_readf_float failed" << std::endl;
	    return;
	}

	m_lastStart = start;
	m_lastCount = readCount;
    }

    for (size_t i = 0; i < count * m_fileInfo.channels; ++i) {
        if (i >= m_bufsiz) {
            std::cerr << "INTERNAL ERROR: WavFileReader::getInterleavedFrames: " << i << " >= " << m_bufsiz << std::endl;
        }
	results.push_back(m_buffer[i]);
    }

    return;
}
示例#16
0
axSOUND_ERROR axAudioBuffer::OpenSoundFile( const string& snd_path )
{
    m_info = new SF_INFO;
    m_path = snd_path;

    if( !( m_sndFile = sf_open( m_path.c_str(), SFM_READ, m_info ) ) )
    {
        return axOPEN_SND_ERROR;
    }

    if( m_buffer )
    {
        delete m_buffer;
        m_buffer = nullptr;
    }

    m_buffer = new axFloat[m_info->frames * m_info->channels];

    /*unsigned int numFrames = */sf_readf_float( m_sndFile, m_buffer, m_info->frames );

    m_start = m_buffer;
    m_end = &m_buffer[ m_info->frames * m_info->channels - 1 ];

    sf_close( m_sndFile );

    return axNO_ERROR;
}
示例#17
0
GObject *phat_audiostream_new( char *filename ) {

    GObject *retval = g_object_new (PHAT_TYPE_AUDIOSTREAM, NULL);

    PhatAudiostream *stream = (PhatAudiostream *)  retval;

    // load file;
    SF_INFO info;
    SNDFILE *file = sf_open( filename, SFM_READ, &info );

    stream->data = malloc( sizeof(float) * info.frames * info.channels );
    if( stream->data == NULL ) {
	printf( "No Mem for audio file\n" );
	exit(20);
    }

    sf_readf_float( file, stream->data, info.frames );
    sf_close( file );

    stream->len = info.frames;
    stream->num_channels = info.channels;

    stream->src_buffer = malloc( sizeof(float) * 4096 * info.channels );
    if( stream->src_buffer == NULL ) {
	printf( "No Mem for Src Buffer\n" );
	exit(20);
    }


    return retval;
}
示例#18
0
ALuint SndFileDecoder::read(ALvoid *ptr, ALuint count)
{
    sf_count_t got = 0;
    if(mSampleType == SampleType::Int16)
        got = sf_readf_short(mSndFile, static_cast<short*>(ptr), count);
    else if(mSampleType == SampleType::Float32)
        got = sf_readf_float(mSndFile, static_cast<float*>(ptr), count);
    return (ALuint)std::max<sf_count_t>(got, 0);
}
示例#19
0
static void *
disk_thread (void *arg)
{	thread_info_t *info = (thread_info_t *) arg ;
	sf_count_t buf_avail, read_frames ;
	jack_ringbuffer_data_t vec [2] ;
	size_t bytes_per_frame = sample_size*info->channels ;

	pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL) ;
	pthread_mutex_lock (&disk_thread_lock) ;

	while (1)
	{	jack_ringbuffer_get_write_vector (ringbuf, vec) ;

		read_frames = 0 ;

		if (vec [0].len)
		{	/* Fill the first part of the ringbuffer. */
			buf_avail = vec [0].len / bytes_per_frame ;
			read_frames = sf_readf_float (info->sndfile, (float *) vec [0].buf, buf_avail) ;
			if (vec [1].len)
			{	/* Fill the second part of the ringbuffer? */
				buf_avail = vec [1].len / bytes_per_frame ;
				read_frames += sf_readf_float (info->sndfile, (float *) vec [1].buf, buf_avail) ;
				} ;
			} ;

		if (read_frames == 0)
			break ; /* end of file? */

		jack_ringbuffer_write_advance (ringbuf, read_frames * bytes_per_frame) ;

		/* Tell process that we've filled the ringbuffer. */
		info->can_process = 1 ;

		/* Wait for the process thread to wake us up. */
		pthread_cond_wait (&data_ready, &disk_thread_lock) ;
		} ;

	/* Tell that we're done reading the file. */
	info->read_done = 1 ;
	pthread_mutex_unlock (&disk_thread_lock) ;

	return 0 ;
} /* disk_thread */
bool BufReadCmd::Stage2()
{
#ifdef NO_LIBSNDFILE
	SendFailure(&mReplyAddress, "/b_read", "scsynth compiled without libsndfile\n");
 	scprintf("scsynth compiled without libsndfile\n");
	return false;
#else
	SF_INFO fileinfo;

	SndBuf *buf = World_GetNRTBuf(mWorld, mBufIndex);
	int framesToEnd = buf->frames - mBufOffset;
	if (framesToEnd <= 0) return true;

	SNDFILE* sf = sf_open(mFilename, SFM_READ, &fileinfo);
	if (!sf) {
		char str[512];
		sprintf(str, "File '%s' could not be opened: %s\n", mFilename, sf_strerror(NULL));
		SendFailureWithIntValue(&mReplyAddress, "/b_read", str, mBufIndex); //SendFailure(&mReplyAddress, "/b_read", str);
		scprintf(str);
		return false;
	}
	if (fileinfo.channels != buf->channels) {
		char str[512];
		sf_close(sf);
		sprintf(str, "Channel mismatch. File '%s' has %d channels. Buffer has %d channels.\n", mFilename, fileinfo.channels, buf->channels);
		SendFailureWithIntValue(&mReplyAddress, "/b_read", str, mBufIndex); //SendFailure(&mReplyAddress, "/b_read", str);
		scprintf(str);
		return false;
	}

	if (mFileOffset < 0) mFileOffset = 0;
	else if (mFileOffset > fileinfo.frames) mFileOffset = fileinfo.frames;
	if (mNumFrames < 0 || mNumFrames + mFileOffset > fileinfo.frames) mNumFrames = fileinfo.frames - mFileOffset;

	if (mNumFrames > framesToEnd) mNumFrames = framesToEnd;

	sf_seek(sf, mFileOffset, SEEK_SET);
	if (mNumFrames > 0) {
		sf_readf_float(sf, buf->data + (mBufOffset * buf->channels), mNumFrames);
	}

	if(buf->sndfile)
		sf_close(buf->sndfile);

	if (mLeaveFileOpen) {
		buf->sndfile = sf;
	} else {
		sf_close(sf);
		buf->sndfile = 0;
	}

	mSampleRate = (double)fileinfo.samplerate;

	return true;
#endif
}
示例#21
0
static RemixCount
remix_sndfile_read_into_chunk (RemixEnv * env, RemixChunk * chunk,
			       RemixCount offset, RemixCount count,
			       int channelname, void * data)
{
  RemixBase * sndfile = (RemixBase *)data;
  RemixPCM * d, * p;
  RemixCount remaining = count, written = 0, n, i;
  RemixSndfileInstance * si = (RemixSndfileInstance *)sndfile->instance_data;

  remix_dprintf ("[remix_sndfile_read_into_chunk] (%p, +%ld) @ %ld\n",
		 sndfile, count, remix_tell (env, sndfile));

  d = &chunk->data[offset];

  n = MIN (remaining, BLOCK_FRAMES);
  if (channelname == 0)
    remix_sndfile_read_update (env, sndfile, n);

  n = MIN (si->pcm_n, remaining);
  
  p = si->pcm;
  p += channelname;
  
  for (i = 0; i < n; i++) {
    *d++ = *p;
    p += si->info.channels;
  }
    
  if (n == 0) { /* EOF */
    n = _remix_pcm_set (d, 0.0, remaining);
  }
  
  remaining -= n;
  written += n;
  
#if 0 /* mono only */
  d = &chunk->data[offset];

  while (remaining > 0) {
    n = MIN (remaining, BLOCK_FRAMES);
    n = sf_readf_float (si->file, d, n);

    if (n == 0) { /* EOF */
      n = _remix_pcm_set (d, 0.0, remaining);
    }

    remaining -= n;
    written += n;

    d += n;
  }
#endif

  return written;
}
示例#22
0
static RemixCount
remix_sndfile_read_update (RemixEnv * env, RemixBase * sndfile,
			   RemixCount count)
{
  RemixSndfileInstance * si = (RemixSndfileInstance *)sndfile->instance_data;

  si->pcm_n = sf_readf_float (si->file, si->pcm, count);

  return si->pcm_n;
}
示例#23
0
void AUD_SndFileReader::read(int& length, bool& eos, sample_t* buffer)
{
	int olen = length;

	length = sf_readf_float(m_sndfile, buffer, length);

	m_position += length;

	eos = length < olen;
}
示例#24
0
	void Sound::createFromFile(const std::string& szFileName) {
#ifndef NO_SOUND
		if(enabled) {
			bool err = false;
			
			//Open stream
			SNDFILE* stream = nullptr;
			SF_INFO info;
			//memset(&info, 0, sizeof(_info));

			std::string path = util::getPath(szFileName);
			FILE* fp = util::ufopen(path, "rb");
			if(!fp) {
				goto error;
			}
			stream = sf_open_fd(fileno(fp), SFM_READ, &info, SF_FALSE);

			if(!stream) {
				goto error;
			}

			//Get size of buffer and allocate memory
			c_samples = info.frames;
			channels = info.channels;
			sample_rate = info.samplerate;
			samples = new float[c_samples * channels];

			if(sf_readf_float(stream, samples, c_samples) != c_samples) {
				goto error;
			}
			goto end;

	error:
			if(samples) {
				delete [] samples;
				samples = nullptr;
			}
			c_samples = 0;
			channels = 0;
			err = true;

	end:
			if(stream) {
				sf_close(stream);
			}
			if(fp) {
				fclose(fp);
			}
			
			if(err) {
				die("Unable to load audio file \"" + path + "\".");
			}
		}
#endif
	}
示例#25
0
static size_t
media_sndfile_read(media_substream *mss, void *outbuf, size_t length)
{
/* read at most `length' frames into `outbuf' */
	/* libsndfile stuff */
	media_sndfile_data *sfd;
	SNDFILE *sf;
	/* media stream stuff */
	Lisp_Media_Stream *ms = mss->up;
	mtype_audio_properties *mtap;
	media_sample_format_t *fmt;
	sf_count_t _read = 0;

	/* check the integrity of the media stream */
	if (media_stream_driver(ms) != MYSELF)
		return 0;
	if (media_substream_type(mss) != MTYPE_AUDIO)
		return 0;

	/* fetch the SNDFILE context and our audio props */
	if ((sfd = media_stream_data(ms)) == NULL ||
	    (sf = sfd->sf) == NULL)
		return 0;
	if (!(mtap = media_substream_type_properties(mss).aprops))
		return 0;

	fmt = mtap->msf;

	switch (sfd->sfinfo->format & 0xFF) {
	case SF_FORMAT_ULAW:
	case SF_FORMAT_ALAW:
	case SF_FORMAT_PCM_U8:
	case SF_FORMAT_PCM_S8:
	case SF_FORMAT_PCM_16:
		_read = sf_readf_short(sf, outbuf, length);
		break;
	case SF_FORMAT_PCM_24:
	case SF_FORMAT_PCM_32:
		_read = sf_readf_int(sf, outbuf, length);
		break;
	case SF_FORMAT_FLOAT:
		_read = sf_readf_float(sf, outbuf, length);
		break;
	default:
		/* be mean */
		abort();
	}

	/* always convert to internal format */
	MEDIA_SAMPLE_FORMAT_UPSAMPLE(fmt)(outbuf, outbuf, _read*mtap->channels);

	SNDFILE_DEBUG_S("read %d frames\n", _read);

	return _read;
}
示例#26
0
/* This routine will be called by the PortAudio engine when audio is needed.
 ** It may called at interrupt level on some machines so don't do anything
 ** that could mess up the system like calling malloc() or free().
 */
static int paCallback(const void *inputBuffer, void *outputBuffer,
        unsigned long framesPerBuffer,
        const PaStreamCallbackTimeInfo* timeInfo,
        PaStreamCallbackFlags statusFlags,
        void *userData)
{
    /* Cast data passed through stream to our structure. */
    paData *data = (paData*)userData;
    float *out = (float*)outputBuffer;
    (void) inputBuffer; /* Prevent unused variable warning. */

    int i, readcount;

    /* read data from file 1 */
    readcount = sf_readf_float (data->infile1, data->buffer1, framesPerBuffer);  

    /* if end of file 1 reached, rewind */
    if (readcount < framesPerBuffer) {
        sf_seek(data->infile1, 0, SEEK_SET);
        readcount = sf_readf_float (data->infile1, data->buffer1+(readcount*STEREO), framesPerBuffer-readcount);  
    }

    /* samples adjusted for volume from each file for each channel */
    for (i = 0; i < framesPerBuffer * STEREO; i+=2) {
        out[i] = (data->amplitude1 * data->buffer1[i]);
        out[i+1] = (data->amplitude1 * data->buffer1[i+1]);
	
    }

	for (i=0; i<FRAMES_PER_BUFFER; i++ ) {
		g_buffer[i] = out[2*i];
	}
	float last_sum_factor = sum_factor;
	sum_factor = getSumOfBuffer(g_buffer);

	final_detail = detail*fabs((sum_factor+last_sum_factor)/2);

    // set flag
    g_ready = true;

    return paContinue;
}
SampleLoader::LoadStatus SampleLoader_SNDFile::load_sample(String p_filename, Sample *p_sample) {
	

	/* HEADER */
	SF_INFO sfinfo;
	memset(&sfinfo,0,sizeof(sfinfo));
	SNDFILE * sfile  =  sf_open(p_filename.utf8().get_data(), SFM_READ, &sfinfo);
	if (sfile==NULL) {

		return LOAD_UNRECOGNIZED;
	}

	if ((sfile!=NULL) && ((sfinfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_RAW)) {
		
		sf_close(sfile);
		return LOAD_UNRECOGNIZED;
	}
	
	/* FORMAT */

	//create 
	p_sample->create(sfinfo.channels,sfinfo.frames);
	p_sample->set_base_freq(sfinfo.samplerate);
	
	
	/* DATA */

	int index=0;

	while (true) {

		int readcount=AUXBUFF_MAX_SIZE/sfinfo.channels;
		int result=sf_readf_float(sfile, auxbuff,readcount);

		for (int i=0;i<result;i++) {

			FrameData f(sfinfo.channels);
			
			for (int j=0;j<sfinfo.channels;j++)
				f.set(j,auxbuff[ sfinfo.channels*i+j ] );

			p_sample->set_frame(index,f);
			index++;
		}

		if (result!=readcount)
			break;
	}

	sf_close(sfile);

	return LOAD_OK;

}
示例#28
0
void AudioIO::readAudioBufferFromFile() {
  float *audioFileBufferPtr = audioFileBuffer;
  int framesLeft = audioParameters.bufferSize;
  while(framesLeft > 0) {
    int framesRead = sf_readf_float(audioInputFile, audioFileBufferPtr, framesLeft);
    if(framesRead < framesLeft)
      sf_seek(audioInputFile, 0, SEEK_SET); // rewind file
    framesLeft -= framesRead;
    audioFileBufferPtr += framesRead * 2;
  }
}
示例#29
0
SINT SoundSourceSndFile::readSampleFrames(
        SINT numberOfFrames, CSAMPLE* sampleBuffer) {
    const sf_count_t readCount =
            sf_readf_float(m_pSndFile, sampleBuffer, numberOfFrames);
    if (0 <= readCount) {
        return readCount;
    } else {
        qWarning() << "Failed to read from libsnd file:" << readCount
                << sf_strerror(m_pSndFile);
        return 0;
    }
}
示例#30
0
/*
 *	length is number of uints that we read.
 */
int32_t	wavFiles::readBuffer (DSPCOMPLEX *data, int32_t length) {
int32_t	i, n;
float	temp [2 * length];

	n = sf_readf_float (filePointer, temp, length);
	if (n < length) {
	   sf_seek (filePointer, 0, SEEK_SET);
	   fprintf (stderr, "End of file, restarting\n");
	}
	for (i = 0; i < n; i ++)
	   data [i] = DSPCOMPLEX (4 * temp [2 * i], 4 * temp [2 * i + 1]);
	return	n & ~01;
}