示例#1
0
bool OGGMusic::Load(const char * filename)
{
	if (ov_fopen((char*)filename,&_ogg_file)!=0)
		return false;	

	_frequency = _ogg_file.vi->rate;
	_channels = _ogg_file.vi->channels;
	_total_time = ov_time_total(&_ogg_file,-1);

	if (_channels!=2 && _channels!=1)
		return false;

	//On alloue tout le temps pour 1sec de musique
	_stream_block_size = _frequency*2*_channels;
	
	_sound_data_size = _total_time*_frequency*2*_channels;

	_sound_data[0] = new char[_stream_block_size];
	_sound_data[1] = new char[_stream_block_size];

	alGenBuffers(2,_buffer);
	alGenSources(1,_source);

	CreateThread(NULL,NULL,_thread_play_pause_stop_wrapper,(void*)this,0,NULL);	

	return true;
}
  pair<ALuint, float> Sound_Buffer::load_ogg_vorbis(const string &
#ifndef DISABLE_AL
    filename
#endif
    ) {

#ifndef DISABLE_AL

    /*** Open VorbisFile ***/

    OggVorbis_File oggFile;
    if(ov_fopen(const_cast<char *>(filename.c_str()), &oggFile))
      return make_pair(AL_NONE, 0.0f);

    /*** Get Information About the Audio File ***/

    vorbis_info *pInfo = ov_info(&oggFile, -1);
    const ALenum format = pInfo->channels == 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
    const ALsizei freq = pInfo->rate;
    const ALsizei bytes_per_sample = format == AL_FORMAT_STEREO16 ? 4 : 2;
    const ogg_int64_t num_samples = ov_pcm_total(&oggFile, -1);
    const ogg_int64_t pcm_size = num_samples * bytes_per_sample;
    const float duration = float(num_samples) / freq;

#ifndef NDEBUG
    if(format == AL_FORMAT_STEREO16)
      cerr << "WARNING: '" << filename << "' is stereo and will be unaffected by the OpenAL positional audio system." << endl;
#endif

    /*** Load the Audio File ***/

    int bytes = 0;
    int buffer_size = int(pcm_size);
    vector<char> buffer( static_cast<size_t>(buffer_size) );
    for(char *begin = &buffer[0], *end = begin + pcm_size;
        begin != end;
        begin += bytes, buffer_size -= bytes) {
      bytes = ov_read(&oggFile, begin, buffer_size, 0, 2, 1, 0);

      if(!bytes) {
        ov_clear(&oggFile);
        throw Sound_Buffer_Init_Failure();
      }
    }

    /*** Generate Audio Buffer ***/

    ALuint bufferID = AL_NONE;
    alGenBuffers(1, &bufferID);
    alBufferData(bufferID, format, &buffer[0], static_cast<ALsizei>(buffer.size()), freq);

    return make_pair(bufferID, duration);

#else

    return make_pair(AL_NONE, 0.0f);

#endif

  }
示例#3
0
void SourceFileOggVorbis::init()
{
	CI_ASSERT( mDataSource );
#if ! defined( CINDER_ANDROID )
	if( mDataSource->isFilePath() ) {
		int status = ov_fopen( mDataSource->getFilePath().string().c_str(), &mOggVorbisFile );
		if( status )
			throw AudioFileExc( string( "Failed to open Ogg Vorbis file with error: " ), (int32_t)status );
	}
	else {
#endif
		mStream = mDataSource->createStream();

		ov_callbacks callbacks;
		callbacks.read_func = readFn;
		callbacks.seek_func = seekFn;
		callbacks.close_func = closeFn;
		callbacks.tell_func = tellFn;

		int status = ov_open_callbacks( this, &mOggVorbisFile, NULL, 0, callbacks );
		CI_VERIFY( status == 0 );

#if ! defined( CINDER_ANDROID )
	}
#endif

	vorbis_info *info = ov_info( &mOggVorbisFile, -1 );
    mNumChannels = info->channels;
    mSampleRate = info->rate;

	ogg_int64_t totalFrames = ov_pcm_total( &mOggVorbisFile, -1 );
    mNumFrames = mFileNumFrames = static_cast<uint32_t>( totalFrames );
}
示例#4
0
文件: ogg.cpp 项目: udeshini14/vrok
int OGGDecoder::open(const char *url)
{

    int ret=ov_fopen(url,&vf);
    if (ret<0){
        DBG("open fail");
        return -1;
    }

    buffer = new float[VPBUFFER_FRAMES*ov_info(&vf,0)->channels];
    half_buffer_size = VPBUFFER_FRAMES*ov_info(&vf,0)->channels*sizeof(float);

    VPBuffer bin;
    bin.srate = ov_info(&vf,0)->rate;
    bin.chans = ov_info(&vf,0)->channels;
    bin.buffer[0] = NULL;
    bin.buffer[1] = NULL;

    owner->setOutBuffers(&bin,&bout);
    for (unsigned i=0;i<VPBUFFER_FRAMES*bout->chans;i++){
        bout->buffer[0][i]=0.0f;
        bout->buffer[1][i]=0.0f;

    }

    return 0;
}
示例#5
0
int SoundSourceOggVorbis::open()
{
    QByteArray qBAFilename = m_qFilename.toLocal8Bit();
#ifdef __WINDOWS__
    if(ov_fopen(qBAFilename.constData(), &vf) < 0) {
        qDebug() << "oggvorbis: Input does not appear to be an Ogg bitstream.";
        filelength = 0;
        return ERR;
    }
#else
    FILE *vorbisfile =  fopen(qBAFilename.constData(), "r");

    if (!vorbisfile) {
        qDebug() << "oggvorbis: cannot open" << m_qFilename;
        return ERR;
    }

    if(ov_open(vorbisfile, &vf, NULL, 0) < 0) {
        qDebug() << "oggvorbis: Input does not appear to be an Ogg bitstream.";
        filelength = 0;
        return ERR;
    }
#endif

    // lookup the ogg's channels and samplerate
    vorbis_info * vi = ov_info(&vf, -1);

    channels = vi->channels;
    m_iSampleRate = vi->rate;

    if(channels > 2){
        qDebug() << "oggvorbis: No support for more than 2 channels!";
        ov_clear(&vf);
        filelength = 0;
        return ERR;
    }

    // ov_pcm_total returns the total number of frames in the ogg file. The
    // frame is the channel-independent measure of samples. The total samples in
    // the file is channels * ov_pcm_total. rryan 7/2009 I verified this by
    // hand. a 30 second long 48khz mono ogg and a 48khz stereo ogg both report
    // 1440000 for ov_pcm_total.
    ogg_int64_t ret = ov_pcm_total(&vf, -1);

    if (ret >= 0) {
        // We pretend that the file is stereo to the rest of the world.
        filelength = ret * 2;
    }
    else //error
    {
      if (ret == OV_EINVAL) {
          //The file is not seekable. Not sure if any action is needed.
          qDebug() << "oggvorbis: file is not seekable " << m_qFilename;
      }
    }

    return OK;
}
        void OggFileStream::init(const ALuint& source,
                                 const int& position_in_file,
                                 const int& position_in_buffer,
                                 const bool& is_event)
        {
          // create buffers for reading in flip mode
          alGenBuffers(2,m_buffers) ;
          
          InternalMessage("Sound", "enter oggreader Init") ;

          // Create Ogg Stream on the file
          m_stream = new OggVorbis_File() ;
          int error = ov_fopen((char*)m_file_name.c_str(),m_stream) ;
          if (error < 0)
          {
            ErrorMessage("[OpenAL::OggReader] Can't read the samples") ;
            return ;
          }

          // Get sound information
          vorbis_info* Infos = ov_info(m_stream,-1) ;

          m_sample_rate = Infos->rate ;
          m_samples_by_buffer = (ALsizei)(Infos->channels * Infos->rate * m_update_time) ;
          switch (Infos->channels)
          {
          case 1:
            m_format = AL_FORMAT_MONO16 ;
            break;
          case 2:
            m_format = AL_FORMAT_STEREO16 ;
            break;
          default:
            ErrorMessage("[OpenAL::OggReader] Audio Format audio not supported (more than 2 channel)") ;
            return ;
          }

          int pos = 0 ;
          if (position_in_file > 0)
          {
            pos = position_in_file-m_samples_by_buffer+position_in_buffer+1 ;
          }
          ov_pcm_seek(m_stream,pos) ;

          // Load the buffers
          loadBuffer(m_buffers[0],is_event) ;
          loadBuffer(m_buffers[1],is_event) ;
          alSourceQueueBuffers(source,2,m_buffers) ;
          if (alGetError() != AL_NO_ERROR)
          {
            InformationMessage("Sound",
                "[OpenAL::OggReader] Impossible to queue the buffers") ;
            return ;
          }

          InternalMessage("Sound", "leave oggreader Init") ;
        }
示例#7
0
static int private_load_vorbis (
	LISndSample* self,
	const char*  file)
{
	int bs = -1;
	int freq;
	long num;
	void* buffer;
	ogg_int64_t pos;
	ogg_int64_t len;
	vorbis_info* info;
	OggVorbis_File vorbis;

	/* Initialize the decoder. */
	num = ov_fopen ((char*) file, &vorbis);
	if (num != 0)
	{
		if (num == OV_EREAD)
			lisys_error_set (EIO, "cannot open `%s'", file);
		else
			lisys_error_set (EINVAL, "cannot read `%s'", file);
		return 0;
	}

	/* Get stream information. */
	info = ov_info (&vorbis, -1);
	freq = info->rate;
	len = 2 * info->channels * ov_pcm_total (&vorbis, -1);
	pos = 0;

	/* Allocate the output buffer. */
	buffer = lisys_malloc (len);
	if (buffer == NULL)
	{
		ov_clear (&vorbis);
		return 0;
	}

	/* Decode the stream. */
	while (1)
	{
		num = ov_read (&vorbis, buffer + pos, len - pos, lisys_endian_big (), 2, 1, &bs);
		if (num <= 0)
			break;
		pos += num;
	}

	/* Upload to OpenAL. */
	if (info->channels == 1)
		private_load_raw (self, AL_FORMAT_MONO16, buffer, len, freq);
	else
		private_load_raw (self, AL_FORMAT_STEREO16, buffer, len, freq);
	ov_clear (&vorbis);
	lisys_free (buffer);

	return 1;
}
示例#8
0
void SoundBuffer::InitOgg( const char * a_filename )
{
#ifdef USE_VORBIS
	// http://www.gamedev.net/page/resources/_/technical/game-programming/introduction-to-ogg-vorbis-r2031
	OggVorbis_File ogg_file;

	// load ogg
    const char * full_path = GetFullPath( a_filename );
	int err_val = ov_fopen( full_path, &ogg_file );
	//int err_val = ov_open_callbacks( nullptr, &ogg_file, (const char*)a_data_file.GetData(), a_data_file.GetNumBytes(), OV_CALLBACKS_STREAMONLY );
	CHECK( err_val == 0, "OGG File load error %d", err_val );
	vorbis_info * ogg_info = ov_info(&ogg_file, -1);
	ASSERT( ogg_info );

	// ogg format
	ALenum al_format;
	if ( ogg_info->channels == 1 ) 
		al_format = AL_FORMAT_MONO16;
	else if ( ogg_info->channels == 2 )
		al_format = AL_FORMAT_STEREO16;
	else
		ERROR_MSG("OGG - Unrecognized num channels : %d", ogg_info->channels );

	// num samples
	ogg_int64_t total_num_pcm_samples = ov_pcm_total( &ogg_file, -1 );
	ASSERT( total_num_pcm_samples > 0 );

	// reserve space for the buffer
	std::vector<char> buffer;
	buffer.reserve( (size_t)(total_num_pcm_samples * 2 * ogg_info->channels) );

	char buff_array[32768];    // Local fixed size array
	int bit_stream = 0;
	int num_bytes_read = 0;

	// read all the data
	do 
	{
		num_bytes_read = ov_read(&ogg_file, buff_array, sizeof(buff_array), 0, 2, 1, &bit_stream);
		buffer.insert(buffer.end(), buff_array, buff_array + num_bytes_read);
	} while (num_bytes_read > 0);
	 
	// check size size
	ASSERT( total_num_pcm_samples * 2 * ogg_info->channels  == buffer.size() );

	// output the data
	ALsizei al_size = buffer.size();
	ALsizei al_freq = ogg_info->rate;
	ASSERT( alIsBuffer(m_id) );
	alBufferData( m_id, al_format, &buffer[0], al_size, al_freq);
	
	// close the file
	ov_clear(&ogg_file);
#endif
}
示例#9
0
文件: Audio.cpp 项目: NickYang/qor
Audio::Stream :: Stream(std::string fn):
    m_Filename(fn)
{
    auto l = Audio::lock();
    
    if(Headless::enabled())
        return;
    
    // clear errors
    clear_errors();
    
    int r;
    if((r = ov_fopen((char*)&fn[0], &m_Ogg)) < 0)
        ERROR(READ, Filesystem::getFileName(fn));
    
    if(check_errors())
        ERROR(READ, Filesystem::getFileName(fn));

    m_VorbisInfo = ov_info(&m_Ogg, -1);
    m_VorbisComment = ov_comment(&m_Ogg, -1);
    
    if(check_errors())
        ERROR(READ, Filesystem::getFileName(fn));
 
    if(m_VorbisInfo->channels == 1)
        m_Format = AL_FORMAT_MONO16;
    else
        m_Format = AL_FORMAT_STEREO16;
    
    alGenBuffers(2, m_Buffers);

    if(check_errors())
        ERROR(READ, Filesystem::getFileName(fn));

    flags |= Source::F_LOOP;

    //std::cout
    //    << "version         " << m_VorbisInfo->version         << "\n"
    //    << "channels        " << m_VorbisInfo->channels        << "\n"
    //    << "rate (hz)       " << m_VorbisInfo->rate            << "\n"
    //    << "bitrate upper   " << m_VorbisInfo->bitrate_upper   << "\n"
    //    << "bitrate nominal " << m_VorbisInfo->bitrate_nominal << "\n"
    //    << "bitrate lower   " << m_VorbisInfo->bitrate_lower   << "\n"
    //    << "bitrate window  " << m_VorbisInfo->bitrate_window  << "\n"
    //    << "\n"
    //    << "vendor " << m_VorbisComment->vendor << "\n";
        
    //for(int i = 0; i < m_VorbisComment->comments; i++)
    //    std::cout << "   " << m_VorbisComment->user_comments[i] << "\n";
        
    //std::cout << std::endl;

    m_bOpen = true;
}
void parse_metadata(const char *path, song_t *song) {
    OggVorbis_File vf;

    int rc = ov_fopen(path, &vf);
    if (rc) {
        fprintf(stderr, "Could not open '%s'\n", path);
        return;
    }

    vorbis_comment *comment = ov_comment(&vf, -1);
    if (comment == NULL) {
        fprintf(stderr, "Could not read comments from '%s'\n", path);
        return;
    }

    song->path = calloc(strlen(path)+1, sizeof(char));
    strcpy(song->path, path);

    char *buf;
    for (int i=0; i < comment->comments; i++) {
        buf = calloc(comment->comment_lengths[i]+1, sizeof(char));
        strncpy(buf, comment->user_comments[i], comment->comment_lengths[i]);
        buf[comment->comment_lengths[i]] = '\0';

        int equals = 0;
        for (; buf[equals] != '=' && equals < strlen(buf); equals++);

        int len = 0;
        if (equals < strlen(buf)) {
            if (! strncmp(buf, ARTIST, strlen(ARTIST))) {
                len = strlen(buf)-strlen(ARTIST)+1;
                song->artist = calloc(len, sizeof(char));
                strncpy(song->artist, buf+equals+1, len);
            } else if (! strncmp(buf, ALBUM, strlen(ALBUM))) {
                len = strlen(buf)-strlen(ALBUM)+1;
                song->album = calloc(len, sizeof(char));
                strncpy(song->album, buf+equals+1, len);
            } else if (! strncmp(buf, TITLE, strlen(TITLE))) {
                len = strlen(buf)-strlen(TITLE)+1;
                song->title = calloc(len, sizeof(char));
                strncpy(song->title, buf+equals+1, len);
            } else if ( !strncmp(buf, TRACKNUMBER, strlen(TRACKNUMBER))) {
                len = strlen(buf)-strlen(TRACKNUMBER);
                song->track = atoi(buf+equals+1);
            }

        }

        free(buf);
    }

    ov_clear(&vf);
}
int
VorbisDecoder_init(decoders_VorbisDecoder *self, PyObject *args, PyObject *kwds) {
    char* filename;
    vorbis_info* info;

    self->open_ok = 0;
    self->channel_count = 0;
    self->rate = 0;
    self->closed = 0;
    self->audiotools_pcm = NULL;

    if (!PyArg_ParseTuple(args, "s", &filename))
        return -1;

    /*open file using reference Ogg Vorbis decoder*/
    switch (ov_fopen(filename, &(self->vorbisfile))) {
    case 0:
    default:
        self->open_ok = 1;
        break;
    case OV_EREAD:
        PyErr_SetString(PyExc_ValueError, "I/O error");
        return -1;
    case OV_ENOTVORBIS:
        PyErr_SetString(PyExc_ValueError, "not a Vorbis file");
        return -1;
    case OV_EVERSION:
        PyErr_SetString(PyExc_ValueError, "Vorbis version mismatch");
        return -1;
    case OV_EBADHEADER:
        PyErr_SetString(PyExc_ValueError, "invalid Vorbis bitstream header");
        return -1;
    case OV_EFAULT:
        PyErr_SetString(PyExc_ValueError, "internal logic fault");
        return -1;
    }

    /*pull stream metadata from decoder*/
    if ((info = ov_info(&(self->vorbisfile), -1)) != NULL) {
        self->channel_count = info->channels;
        self->rate = info->rate;
    } else {
        PyErr_SetString(PyExc_ValueError, "unable to get Vorbis info");
        return -1;
    }

    /*open FrameList creator*/
    if ((self->audiotools_pcm = open_audiotools_pcm()) == NULL)
        return -1;

    return 0;
}
示例#12
0
static int
oggfile_open(struct oggfile *of, char *path)
{
	assert(of != NULL);
	assert(path != NULL);

	if (ov_fopen((char *)path, &of->ovf) != 0)
		return (1);

	of->path = path;

	return (0);
}
示例#13
0
SoundBuffer::SoundBuffer(const FilePath& path) {
  OggVorbis_File file;
  CHECK(ov_fopen(path.getPath(), &file) == 0) << "Error opening audio file: " << path;
  vorbis_info* info = ov_info(&file, -1);
  ov_raw_seek(&file, 0);
  vector<char> buffer = readSoundData(file);
  OpenalId id;
  AL(alGenBuffers(1, &id));
  AL(alBufferData(id, (info->channels > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16, buffer.data(), buffer.size(),
      info->rate));
  bufferId = id;
  ov_clear(&file);
}
示例#14
0
bool OggStream::open(string path)
{
    int error = ov_fopen((char*)path.c_str(), &mStream);

    ostringstream oss;
    oss << "AudioFile:" << path;
    mStreamInfo = oss.str();

    if(error) {
        switch(error)
        {
            case OV_EREAD:
                LOG4CXX_ERROR(narratorOsLog, "File " << path << ": A read from media returned an error");
                break;
            case OV_ENOTVORBIS:
                LOG4CXX_ERROR(narratorOsLog, "File " << path << ": Bitstream is not Vorbis data");
                break;
            case OV_EVERSION:
                LOG4CXX_ERROR(narratorOsLog, "File " << path << ": Vorbis version mismatch");
                break;
            case OV_EBADHEADER:
                LOG4CXX_ERROR(narratorOsLog, "File " << path << ": Invalid Vorbis bitstream header");
                break;
            case OV_EFAULT:
                LOG4CXX_ERROR(narratorOsLog, "File " << path << ": Internal logic fault");
                break;
            default:
                LOG4CXX_ERROR(narratorOsLog, "File " << path << ": unknown error occurred");
                break;
        }
        return false;
    }

    vorbis_info *vi = ov_info(&mStream,-1);

    isOpen = true;
    mChannels = vi->channels;
    mRate = vi->rate;

    /*
       char **ptr = ov_comment(&mStream,-1)->user_comments;
       while(*ptr){
       LOG4CXX_DEBUG(narratorOsLog, "comment: " << *ptr);
       ++ptr;
       }

       size_t total_size = ov_pcm_total(&mStream, -1);
       LOG4CXX_DEBUG(narratorOsLog, "total size: " << total_size);
    */
    return true;
}
示例#15
0
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;
}
示例#16
0
static DWORD ovGetPcmSize(const char* filename)
{
	OggVorbis_File ovf;
	int error;
	DWORD dwPCMBytes;

	error = ov_fopen(filename, &ovf);
	if(error != OV_SUCCESSFUL)
	{
		return 0;
	}
	dwPCMBytes = ovGetPcmSize(&ovf);
	ov_clear(&ovf);
	return dwPCMBytes;
}
示例#17
0
SoundBuffer *load_ogg_from_file(const std::string &path)
{
	OggVorbis_File oggFile;

	// Try opening the given file.
	// This requires libvorbis >= 1.3.2, as
	// previous versions expect a non-const char *
	if (ov_fopen(path.c_str(), &oggFile) != 0) {
		infostream << "Audio: Error opening " << path
			<< " for decoding" << std::endl;
		return NULL;
	}

	return load_opened_ogg_file(&oggFile, path);
}
示例#18
0
void
AudioManager::Player::Play(const Ogre::String &file)
{
    boost::recursive_mutex::scoped_lock lock(*m_UpdateMutex);

    // open vorbis file
    if(ov_fopen(const_cast<char*>(file.c_str()), &m_VorbisFile))
    {
        LOG_ERROR("Can't play file \"" + file + "\".");
        return;
    }

    // get file info
    m_VorbisInfo = ov_info(&m_VorbisFile, -1.0f);

    // create sound source
    alGenSources(1, &m_Source);

    // create buffers
    ALuint buffers[m_ChannelBufferNumber];
    alGenBuffers(m_ChannelBufferNumber, buffers);

    // set source parameters
    alSourcei(m_Source, AL_LOOPING, AL_FALSE);

    // fill buffers
    for(int i = 0; i < m_ChannelBufferNumber; ++i)
    {
        ALsizei buffer_size = FillBuffer();

        if(buffer_size)
        {
            alBufferData(buffers[i], m_VorbisInfo->channels ==
                         1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16,
                         (const ALvoid*)AudioManager::getSingleton().m_Buffer,
                         (ALsizei)buffer_size, (ALsizei)m_VorbisInfo->rate);
            alSourceQueueBuffers(m_Source, 1, &buffers[i]);
        }
        else
        {
            m_StreamFinished = true;
            alDeleteBuffers(1, &buffers[i]);
        }
    }

    // start playback
    alSourcePlay(m_Source);
}
示例#19
0
 bool AudioDecoderOgg::open(const char* path)
 {
     std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
     if (0 == ov_fopen(FileUtils::getInstance()->getSuitableFOpen(fullPath).c_str(), &_vf))
     {
         // header
         vorbis_info* vi = ov_info(&_vf, -1);
         _sampleRate = static_cast<uint32_t>(vi->rate);
         _channelCount = vi->channels;
         _bytesPerFrame = vi->channels * sizeof(short);
         _totalFrames = static_cast<uint32_t>(ov_pcm_total(&_vf, -1));
         _isOpened = true;
         return true;
     }
     return false;
 }
bool FileFormatVorbis::Open(QString& filename)
{
	int result = ov_fopen(filename.toStdString().c_str(), _oggVorbisFile);

	if( result < 0)
	{
		//fclose(_musicFile);
#ifdef WIN32
		MessageBox( QMessageBox::Critical, QString::Format("Could not open ogg file '%s': %s", filename, VorbisErrorString(result)), "Error", QMessageBox::Ok );
#endif
		return false;
	}

	_vorbisInfo = ov_info(_oggVorbisFile, -1);
	_vorbisComment = ov_comment(_oggVorbisFile, -1);

	return true;
}
示例#21
0
文件: oggacd.c 项目: blabber/oggacd
int
getlen(char *path, double *len)
{
        OggVorbis_File  vf;

        assert(path != NULL);

        if (ov_fopen(path, &vf) != 0) {
                warn("ov_fopen(\"%s\", ...)", path);
                return (-1);
        }
        if ((*len = ov_time_total(&vf, -1)) == OV_EINVAL) {
                errx(EX_SOFTWARE, "ov_time_total");
        }
        if (ov_clear(&vf) != 0)
                errx(EX_SOFTWARE, "ov_clear");

        return (0);
}
示例#22
0
int vorbis_source_init(audio_source *src, const char* file) {
    vorbis_source *local;
    int ret;

    // Init local struct
    local = malloc(sizeof(vorbis_source));

    // Try to open up the audio file
    ret = ov_fopen(file, &local->src_file);
    if(ret != 0) {
        PERROR("Vorbis Source: File '%s' could not be opened: ", file, vorbis_text_error(ret));
        goto error_1;
    }

    // Get file information
    vorbis_info *vi = ov_info(&local->src_file, -1);
    char **comment_ptr = ov_comment(&local->src_file, -1)->user_comments;

    // Audio information
    source_set_frequency(src, vi->rate);
    source_set_bytes(src, 2);
    source_set_channels(src, vi->channels);

    // Set callbacks
    source_set_userdata(src, local);
    source_set_update_cb(src, vorbis_source_update);
    source_set_close_cb(src, vorbis_source_close);

    // Some debug info
    DEBUG("Vorbis Source: Loaded file '%s' succesfully (%d Hz, %d ch).", 
        file, vi->rate, vi->channels);
    while(*comment_ptr) {
        DEBUG(" * Comment: %s", *comment_ptr);
        ++comment_ptr;
    }

    // All done
    return 0;
error_1:
    free(local);
    return 1;
}
示例#23
0
    void AudioFile::open(const std::string& path)
    {
        if(mFile)
        {
            ov_clear(mFile);
            delete mFile;
        }

        mFile = new OggVorbis_File;

        if(ov_fopen(path.c_str(), mFile))
        {
            throw AudioFileNotFoundException("Error when trying to load audio file '" + path + "!");
        }

        vorbis_info* info = ov_info(mFile, -1);

        mChannelCount = info->channels;
        mSampleRate = info->rate;
        mSampleAmount = 2 * (size_t)ov_pcm_total(mFile, -1);
    }
示例#24
0
文件: oggfile.c 项目: blabber/oggquiz
static int
fill_comments(struct ogg_context *ctx, struct ogg_oggfile *ogg)
{
    OggVorbis_File  ovf;
    vorbis_comment *ovc;
    char           *key, *value;
    int             i;

    assert(ctx != NULL);
    assert(ogg != NULL);

    if (ov_fopen(ogg->filename, &ovf) != 0) {
        warnx("could not open file: %s", ogg->filename);
        return (1);
    }
    if ((ovc = ov_comment(&ovf, -1)) == NULL) {
        warnx("could not read comments for file: %s", ogg->filename);
        return (1);
    }
    for (i = 0; i < ovc->comments; i++) {
        value = ovc->user_comments[i];
        key = strsep(&value, "=");
        if (strcasecmp(key, "artist") == 0)
            do_iconv(ctx, value, ogg->artist, sizeof(ogg->artist));
        else if (strcasecmp(key, "album") == 0)
            do_iconv(ctx, value, ogg->album, sizeof(ogg->album));
        else if (strcasecmp(key, "title") == 0)
            do_iconv(ctx, value, ogg->title, sizeof(ogg->title));
        if (ogg->artist == NULL || ogg->album == NULL || ogg->title == NULL) {
            warnx("insufficient comments for file: %s", ogg->filename);
            return (1);
        }
    }

    if (ov_clear(&ovf) != 0)
        warnx("could not close file: %s", ogg->filename);

    return (0);
}
  Sound_Stream_AL::Sound_Stream_AL(const String &path, const bool &looping_, const float &time_)
    : buffers_used(0),
    looping(looping_)
  {
    if(!dynamic_cast<Sound_Renderer_AL *>(&get_Sound().get_Renderer()))
      throw Sound_Stream_Init_Failure();

    const int result = ov_fopen((path + ".ogg").c_str(), &oggStream);
    if(result < 0)
      throw Sound_Stream_Ogg_Read_Failure();

    vorbisInfo = ov_info(&oggStream, -1);
    vorbisComment = ov_comment(&oggStream, -1);
 
    if(vorbisInfo->channels == 1)
        format = AL_FORMAT_MONO16;
    else
        format = AL_FORMAT_STEREO16;

    ov_time_seek(&oggStream, time_);

    Sound_Renderer_AL::alGenBuffers()(NUM_BUFFERS, buffers);
    Sound_Renderer_AL::alGenSources()(1, &source);

    ALfloat pos[3] = {0.0f, 0.0f, 0.0f};
    Sound_Renderer_AL::alSourcefv()(source, AL_POSITION,        pos    );
    Sound_Renderer_AL::alSourcefv()(source, AL_VELOCITY,        pos    );
    Sound_Renderer_AL::alSourcefv()(source, AL_DIRECTION,       pos    );
    Sound_Renderer_AL::alSourcef() (source, AL_ROLLOFF_FACTOR,  0.0    );
    Sound_Renderer_AL::alSourcei() (source, AL_SOURCE_RELATIVE, AL_TRUE);

    const ALenum error = Sound_Renderer_AL::alGetError()();
    if(error != AL_NO_ERROR) {
      destroy();
      std::cerr << "OpenAL error: " << Sound_Renderer_AL::errorString(error) << std::endl;
      throw Sound_Stream_Init_Failure();
    }
  }
示例#26
0
Result SoundSourceOggVorbis::tryOpen(const AudioSourceConfig& /*audioSrcCfg*/) {
    const QByteArray qbaFilename(getLocalFileNameBytes());
    if (0 != ov_fopen(qbaFilename.constData(), &m_vf)) {
        qWarning() << "Failed to open OggVorbis file:" << getUrlString();
        return ERR;
    }

    if (!ov_seekable(&m_vf)) {
        qWarning() << "OggVorbis file is not seekable:" << getUrlString();
        return ERR;
    }

    // lookup the ogg's channels and sample rate
    const vorbis_info* vi = ov_info(&m_vf, kCurrentBitstreamLink);
    if (!vi) {
        qWarning() << "Failed to read OggVorbis file:" << getUrlString();
        return ERR;
    }
    setChannelCount(vi->channels);
    setFrameRate(vi->rate);
    if (0 < vi->bitrate_nominal) {
        setBitrate(vi->bitrate_nominal / 1000);
    } else {
        if ((0 < vi->bitrate_lower) && (vi->bitrate_lower == vi->bitrate_upper)) {
            setBitrate(vi->bitrate_lower / 1000);
        }
    }

    ogg_int64_t pcmTotal = ov_pcm_total(&m_vf, kEntireBitstreamLink);
    if (0 <= pcmTotal) {
        setFrameCount(pcmTotal);
    } else {
        qWarning() << "Failed to read total length of OggVorbis file:" << getUrlString();
        return ERR;
    }

    return OK;
}
示例#27
0
//--------------------------------------------------------------------------------------------
//	ogg形式をPCM形式へデコードし、DSのバッファに書き込みます
//--------------------------------------------------------------------------------------------
static int ovCreateBuffer(OggVorbis_File* ovf_ptr, int bufNumber, const char* filename, DWORD dwSize)
{
	int errorNo;

//	ファイルを開き、oggでなければエラー番号を返す
	ovInitOggEnv(ovf_ptr);
	errorNo = ov_fopen(filename, ovf_ptr);
	if(errorNo != OV_SUCCESSFUL)	return errorNo;

//	PCMの形式をある程度調べる
//	サンプリングレートとチャンネル数のみ?
	vorbis_info *info = ov_info( ovf_ptr, -1 );
	ogg_int64_t t = ov_pcm_total(ovf_ptr, -1);

//	DirectSoundBuffer設定
	WAVEFORMATEX wf;
	//さて、デコードしたPCMのビットレート16を自動的に求めるには…
	dsSetWaveFormat(&wf, info->rate, info->channels, OV_PCM_BITRATE);
	dwSize = dwSize == 0 ? ovGetPcmSize(ovf_ptr): dwSize;
	dsCreateSoundBuffer(bufNumber, &wf, dwSize);

	return OV_SUCCESSFUL;
}
示例#28
0
//This function will open up a specified .ogg file
bool DIZ_OGGSTREAM::loadFile(char fname[]) {
	//Declare an error-checking variable
	int result;

	//Attempt to open the specified file and check for an error
	result = ov_fopen(fname, &oggFile);
	if (result < 0) {
		return false;
	}

	//Retrieve some info about our file
	vorbisInfo = ov_info(&oggFile, -1);

	//Check our channels info and manually set our format accordingly
	if (vorbisInfo->channels == 1) {
		format = AL_FORMAT_MONO16;
	}else {
		format = AL_FORMAT_STEREO16;
	}

	//And return true for A-OK
	return true;
}
示例#29
0
bool AudioSourceOGG::Open(const char* Filename)
{
#if !(defined WIN32) || (defined MINGW)
    int32 retv = ov_fopen(Filename, &mOggFile);
#else
    FILE* fp = _wfopen(Utility::Widen(Filename).c_str(), L"rb");
    int retv = -1;

    if (fp)
        retv = ov_open_callbacks(static_cast<void*>(fp), &mOggFile, nullptr, 0, fileInterfaceOgg);
#endif

#ifndef NDEBUG
    dFILENAME = Filename;
#endif

#if !(defined WIN32) || (defined MINGW)
    if (retv == 0)
#else
    if (retv == 0 && fp)
#endif
    {
        info = ov_info(&mOggFile, -1);
        comment = ov_comment(&mOggFile, -1);

        mIsValid = true;
        mIsDataLeft = true;
    }
    else
    {
        mIsValid = false;
        Log::Printf("Failure loading ogg file: %s (%d)\n", Filename, retv);
    }

    return mIsValid;
}
示例#30
0
std::string GetOggTitle(std::string file)
{
    OggVorbis_File f;
    std::string result = "";
    if (ov_fopen(file.c_str(), &f) == 0)
    {
        vorbis_comment *comment = ov_comment(&f, -1);

        for (int i = 0; i < comment->comments; i++)
        {
            std::string user_comment = comment->user_comments[i];
            auto splitvec = Utility::TokenSplit(user_comment, "=");
            if (splitvec[0] == "TITLE")
            {
                result = splitvec[1];
                break;
            }
        }

        ov_clear(&f);
    }

    return result;
}