当前位置: 首页 > 工具软件 > OpenAL > 使用案例 >

OpenAL 使用基本流程

鞠修雅
2023-12-01

1. 初始化

        ALCcontext* p_context;
        ALCdevice* p_device;
        ALuint ui_source;
        ALuint m_buffers[MAX_CACHE];
        std::list<ALuint> m_buffer_queue;

        p_device = alcOpenDevice(NULL);
        p_context = alcCreate(p_device, NULL);
        alcMakeContextCurrent(p_context);
        alGenBuffers(MAX_SIZE, m_buffers);
        alGenSource(1, &p_source);
        for(auto buf : m_buffers)
        {
            m_buffer_queue.push_back(buf);
        }

2. 设置音效

alListenerf(AL_GAIN, 1.45f);

3. 播放

播放最简单的流程就是:
- 加载音频数据(PS:必须是Raw Data)
- 把数据写入buffer: alBufferData
- alSourcePlay

支持缓冲区的播放:
- 加载音频数据
- 回收Buffer : alSourceUnqueueBuffers
- 把数据写入buffer: alBufferData
- 将buffer放回缓冲区:alSourceQueueBuffers
- 播放: alSourcePlay

具体流程如下:
PS:下面代码是摘出来的,不一定可以运行,看看即可

while(b_break)
{
    //Read Data
    int size= ReadData(buffer);

    //recycle buffers
    ALint i_num;
    alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &i_num);
    ALuint buffers[MAX_SIZE];
    alSourceUnqueueBuffers(ui_source, i_num, buffers);
    for(int i = 0; i <= i_num; ++i)
    {
        m_bufferQueue.push_back(buffers[i]);
    }

    //push data to al buffers
    alBuf = m_buffer_queue.front();
    alBufferData(alBuf, AL_FORMAT_MONO16, buffer, size * kByte, header->samplesPerSec);
    alSourceQueueBuffers(ui_source, 1, &alBuf);

   //play
   ALint bufferQueued;
   alGetSourcei(ui_source, AL_BUFFERS_QUEUED, &bufferQueued);
   if(bufferQueued != 0)
       alSourcePlay(m_source);
}

3. 退出

            //stop
            alSourceStop(ui_source);

            //release
            alcMakeContextCurrent(p_context)
            alDeleteSources(1, &ui_source);
            m_source = 0;

            alDeleteBuffers(MAX_CACHE, m_buffer);
            memset(m_buffer, 0, sizeof(m_buffer));

            alcMakeContextCurrent(nullptr);
            alcDestroyContext(p_context);
            m_context = nullptr;
            alcCloseDevice(p_device);
            p_device = nullptr;
            m_buffer_queue.clear();
 类似资料: