幾種播放音頻文件的方式(十三) —— OpenAL框架之分步解析(二)

版本記錄

版本號 時間
V1.0 2017.12.29

前言

ios系統中有很多方式可以播放音頻文件,這里我們就詳細的說明下播放音樂文件的原理和實例。感興趣的可以看我寫的上面幾篇。
1. 幾種播放音頻文件的方式(一) —— 播放本地音樂
2. 幾種播放音頻文件的方式(二) —— 音效播放
3. 幾種播放音頻文件的方式(三) —— 網絡音樂播放
4. 幾種播放音頻文件的方式(四) —— 音頻隊列服務(Audio Queue Services)(一)
5. 幾種播放音頻文件的方式(五) —— 音頻隊列服務(Audio Queue Services)簡介(二)
6. 幾種播放音頻文件的方式(六) —— 音頻隊列服務(Audio Queue Services)之關于音頻隊列(三)
7. 幾種播放音頻文件的方式(七) —— 音頻隊列服務(Audio Queue Services)之錄制音頻(四)
8. 幾種播放音頻文件的方式(八) —— 音頻隊列服務(Audio Queue Services)之播放音頻(五)
9. 幾種播放音頻文件的方式(九) —— Media Player框架之基本概覽(一)
10. 幾種播放音頻文件的方式(十) —— Media Player框架之簡單播放音頻示例(二)
11. 幾種播放音頻文件的方式(十一) —— AudioUnit框架之基本概覽(一)
12. 幾種播放音頻文件的方式(十二) —— OpenAL框架之基本概覽(一)

分步解析

這一篇文章主要就是對OpenAL播放音頻的過程進行分步解析,文章內容來自別人,下面給出鏈接,致敬原作者—— IOS使用OpenAL播放音頻文件。

其實,不僅可以參考這個作者所寫的內容,我們還可以參考蘋果官網給出的demo,OpenALExampleGLAirplay。

這里我們只談最基本的實現,加載聲音文件,播放聲音。至于3D音效,多普勒效應環境音效設置,聲音位置,收聽位置等都不進行配置。


導入平臺頭文件

#include <stddef.h>  
#include <Foundation/Foundation.h>  
#include <AudioToolbox/AudioToolbox.h>  
#include <OpenAL/OpenAL.h>  

文件需要使用.m文件,因為需要使用Foundation.h的功能來加載Bundle的聲音文件。m后綴文件是c和objc混編的文件類型。AudioToolbox可以對音頻文件信息的解析和設置,以配合OpenAL的使用。


初始化OpenAL

下面還是直接看代碼。

static ALCdevice*                device                 = NULL;  
static ALCcontext*               context                = NULL;  
static alBufferDataStaticProcPtr alBufferDataStaticProc = NULL;  
  
  
struct AudioPlayer  
{  
    ALuint sourceId;  
    ALuint bufferId;  
};  
  
static void Init()  
{  
    // get static buffer data API  
    alBufferDataStaticProc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic");  
      
    // create a new OpenAL Device  
    // pass NULL to specify the system’s default output device  
    device = alcOpenDevice(NULL);  
      
    if (device != NULL)  
    {  
        // create a new OpenAL Context  
        // the new context will render to the OpenAL Device just created  
        context = alcCreateContext(device, 0);  
          
        if (context != NULL)  
        {  
            // make the new context the Current OpenAL Context  
            alcMakeContextCurrent(context);  
        }  
    }  
    else  
    {  
        ALogE("Audio Init failed, OpenAL can not open device");  
    }  
      
    // clear any errors  
    alGetError();  
}  
  • OpenAL全局只需要一個ALCdeviceALCcontext
  • 我們抽象了一個AudioPlayer,用來對應一個播放器,bufferId就是加載到內存的音頻數據,sourceId是對應OpenAL播放器。
  • alBufferDataStatic是OpenAL的一個擴展,相對于alBufferData來說的。功能是加載音頻數據到內存并關聯到bufferId。只不過,alBufferData會拷貝音頻數據所以調用后,我們可以free掉音頻數據。而alBufferDataStatic并不會拷貝,所以音頻數據data我們要一直保留并自己管理。

獲取適合OpenAL使用的音頻數據

我們需要加載聲音文件,解析音頻數據,修改音頻數據格式為OpenAL需要的,獲取最終的可以傳遞給OpenAL使用的音頻數據。這幾步封裝了一個函數,先解釋在看完整的代碼。

  • 首先我們要獲取Bundle的文件路徑。
  • 然后,利用AudioToolBox的功能來讀取并解析這個數據。OpenAL加載數據到Buffer,需要音頻的采樣頻率,通道數,碼率,數據大小等信息。
  • 接著,OpenAL只能播放特定格式和屬性的音頻文件。再次使用AudioToolBox的功能來對音頻數據進行設置,以達到需求。
  • 最后,把處理好的數據和信息返回。

下面我們看代碼。

static inline void* GetAudioData(char* filePath, ALsizei* outDataSize, ALenum* outDataFormat, ALsizei* outSampleRate)  
{  
    AudioStreamBasicDescription fileFormat;  
    AudioStreamBasicDescription outputFormat;  
    SInt64                      fileLengthInFrames = 0;  
    UInt32                      propertySize       = sizeof(fileFormat);  
    ExtAudioFileRef             audioFileRef       = NULL;  
    void*                       data               = NULL;  
  
    NSString*                   path               = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:filePath] ofType:nil];  
    CFURLRef                    fileUrl            = CFURLCreateWithString(kCFAllocatorDefault, (CFStringRef) path, NULL);  
    OSStatus                    error              = ExtAudioFileOpenURL(fileUrl, &audioFileRef);  
      
    CFRelease(fileUrl);  
      
    if (error != noErr)  
    {  
        ALogE("Audio GetAudioData ExtAudioFileOpenURL failed, error = %x, filePath = %s", (int) error, filePath);  
        goto label_exit;  
    }  
      
    // get the audio data format  
    error = ExtAudioFileGetProperty(audioFileRef, kExtAudioFileProperty_FileDataFormat, &propertySize, &fileFormat);  
      
    if (error != noErr)  
    {  
        ALogE("Audio GetAudioData ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) failed, error = %x, filePath = %s", (int) error, filePath);  
        goto label_exit;  
    }  
      
    if (fileFormat.mChannelsPerFrame > 2)  
    {  
        ALogE("Audio GetAudioData unsupported format, channel count = %u is greater than stereo, filePath = %s", fileFormat.mChannelsPerFrame, filePath);  
        goto label_exit;  
    }  
      
    // set the client format to 16 bit signed integer (native-endian) data  
    // maintain the channel count and sample rate of the original source format  
    outputFormat.mSampleRate       = fileFormat.mSampleRate;  
    outputFormat.mChannelsPerFrame = fileFormat.mChannelsPerFrame;  
    outputFormat.mFormatID         = kAudioFormatLinearPCM;  
    outputFormat.mBytesPerPacket   = outputFormat.mChannelsPerFrame * 2;  
    outputFormat.mFramesPerPacket  = 1;  
    outputFormat.mBytesPerFrame    = outputFormat.mChannelsPerFrame * 2;  
    outputFormat.mBitsPerChannel   = 16;  
    outputFormat.mFormatFlags      = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger;  
      
    // set the desired client (output) data format  
    error = ExtAudioFileSetProperty(audioFileRef, kExtAudioFileProperty_ClientDataFormat, sizeof(outputFormat), &outputFormat);  
      
    if(error != noErr)  
    {  
        ALogE("Audio GetAudioData ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) failed, error = %x, filePath = %s", (int) error, filePath);  
        goto label_exit;  
    }  
      
    // get the total frame count  
    propertySize = sizeof(fileLengthInFrames);  
    error        = ExtAudioFileGetProperty(audioFileRef, kExtAudioFileProperty_FileLengthFrames, &propertySize, &fileLengthInFrames);  
      
    if(error != noErr)  
    {  
        ALogE("Audio GetAudioData ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) failed, error = %x, filePath = %s", (int) error, filePath);  
        goto label_exit;  
    }  
      
//--------------------------------------------------------------------------------------------------  
      
    // read all the data into memory  
    UInt32 framesToRead = (UInt32) fileLengthInFrames;  
    UInt32 dataSize     = framesToRead * outputFormat.mBytesPerFrame;  
      
    *outDataSize        = (ALsizei) dataSize;  
    *outDataFormat      =  outputFormat.mChannelsPerFrame > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;  
    *outSampleRate      = (ALsizei) outputFormat.mSampleRate;  
  
    int index           = AArrayStrMap->GetIndex(fileDataMap, filePath);  
      
    if (index < 0)  
    {  
        data = malloc(dataSize);  
          
        if (data != NULL)  
        {  
            AudioBufferList dataBuffer;  
            dataBuffer.mNumberBuffers              = 1;  
            dataBuffer.mBuffers[0].mDataByteSize   = dataSize;  
            dataBuffer.mBuffers[0].mNumberChannels = outputFormat.mChannelsPerFrame;  
            dataBuffer.mBuffers[0].mData           = data;  
              
            // read the data into an AudioBufferList  
            error = ExtAudioFileRead(audioFileRef, &framesToRead, &dataBuffer);  
              
            if(error != noErr)  
            {  
                free(data);  
                data = NULL; // make sure to return NULL  
                ALogE("Audio GetAudioData ExtAudioFileRead failed, error = %x, filePath = %s", (int) error, filePath);  
                goto label_exit;  
            }  
        }  
          
        AArrayStrMapInsertAt(fileDataMap, filePath, -index - 1, data);  
    }  
    else  
    {  
        data = AArrayStrMapGetAt(fileDataMap, index, void*);  
    }  
      
      
    label_exit:  
      
    // dispose the ExtAudioFileRef, it is no longer needed  
    if (audioFileRef != 0)  
    {  
        ExtAudioFileDispose(audioFileRef);  
    }  
      
    return data;  
}  

這里,我使用了ArrayStrMap結構其實就是一個dictionary,用文件路徑緩存了最終的data文件。因為,我會使用alBufferDataStatic,所以最終的data文件由我自己管理。并且同一個音頻文件數據總是相同的,我就不再去頻繁的free在malloc了。

outputFormat就是我們需要的音頻格式,使用ExtAudioFileSetProperty能夠讓我們把原音頻數據格式進行轉換。這樣,我們就可以使用各種音頻文件格式來播放了,比如mp3,wav等等。


利用音頻文件數據,生成我們的播放器對象

  • 首先,生成bufferIdsourceId。
  • 然后,把音頻數據關聯到bufferId,把bufferId關聯到sourceId。
  • 最后,sourceId代表就是OpenAL的播放器,可以設置各種屬性。
  • 那么,當我們需要銷毀播放器的時候,主要也就是銷毀sourceIdbufferId
static inline void InitPlayer(char* filePath, AudioPlayer* player)  
{  
    ALenum  error;  
    ALsizei size;  
    ALenum  format;  
    ALsizei freq;  
    void*   data = GetAudioData(filePath, &size, &format, &freq);  
      
    if ((error = alGetError()) != AL_NO_ERROR)  
    {  
        ALogE("Audio InitPlayer failed, error = %x, filePath = %s", error, filePath);  
    }  
      
    alGenBuffers(1, &player->bufferId);  
    if((error = alGetError()) != AL_NO_ERROR)  
    {  
        ALogE("Audio InitPlayer generate buffer failed, error = %x, filePath = %s", error, filePath);  
    }  
      
    // use the static buffer data API  
    // the data will not copy in buffer so can not free data until buffer deleted  
    alBufferDataStaticProc(player->bufferId, format, data, size, freq);  
      
    if((error = alGetError()) != AL_NO_ERROR)  
    {  
        ALogE("Audio InitPlayer attach audio data to buffer failed, error = %x, filePath = %s", error, filePath);  
    }  
      
//--------------------------------------------------------------------------------------------------  
      
    alGenSources(1, &player->sourceId);  
    if((error = alGetError())!= AL_NO_ERROR)  
    {  
        ALogE("Audio InitPlayer generate source failed, error = %x, filePath = %s", error, filePath);  
    }  
      
    // turn Looping off  
    alSourcei(player->sourceId,                        AL_LOOPING, AL_FALSE);  
      
    // set Source Position  
    alSourcefv(player->sourceId, AL_POSITION,          (const ALfloat[]) {0.0f, 0.0f, 0.0f});  
      
    // set source reference distance  
    alSourcef(player->sourceId,  AL_REFERENCE_DISTANCE, 0.0f);  
      
    // attach OpenAL buffer to OpenAL Source  
    alSourcei(player->sourceId,  AL_BUFFER,             player->bufferId);  
      
    if((error = alGetError()) != AL_NO_ERROR)  
    {  
        ALogE("Audio InitPlayer attach buffer to source failed, error = %x, filePath = %s", error, filePath);  
    }  
}  


設置播放器的各種屬性

tatic void SetLoop(AudioPlayer* player, bool isLoop)  
{  
    ALint isLoopEnabled;  
    alGetSourcei(player->sourceId, AL_LOOPING, &isLoopEnabled);  
      
    if (isLoopEnabled == isLoop)  
    {  
        return;  
    }  
      
    alSourcei(player->sourceId, AL_LOOPING, (ALint) isLoop);  
}  
  
  
static void SetVolume(AudioPlayer* player, int volume)  
{  
    ALogA(volume >= 0 && volume <= 100, "Audio SetVolume volume %d not in [0, 100]", volume);  
    alSourcef(player->sourceId, AL_GAIN, volume / 100.0f);  
      
    ALenum error = alGetError();  
    if(error != AL_NO_ERROR)  
    {  
        ALogE("Audio SetVolume error = %x", error);  
    }  
}  
  
  
static void SetPlay(AudioPlayer* player)  
{  
    alSourcePlay(player->sourceId);  
      
    ALenum error = alGetError();  
    if(error != AL_NO_ERROR)  
    {  
        ALogE("Audio SetPlay error = %x", error);  
    }  
}  
  
  
static void SetPause(AudioPlayer* player)  
{  
    alSourcePause(player->sourceId);  
      
    ALenum error = alGetError();  
    if(error != AL_NO_ERROR)  
    {  
        ALogE("Audio SetPause error = %x", error);  
    }  
}  
  
  
static bool IsPlaying(AudioPlayer* player)  
{  
    ALint state;  
    alGetSourcei(player->sourceId, AL_SOURCE_STATE, &state);  
      
    return state == AL_PLAYING;  
}  

OpenAL并沒有播放完成的回調

OpenAL并沒有播放完成的回調,所以我們需要在Update中不斷的檢測播放器的狀態。如果不是循環播放的聲音,我們就可以刪除它,也可以回調給應用程序做其它操作。

static void Update(float deltaSeconds)  
{  
    for (int i = destroyList->size - 1; i > -1; i--)  
    {  
        AudioPlayer* player = AArrayListGet(destroyList, i, AudioPlayer*);  
          
        ALint state;  
        alGetSourcei(player->sourceId, AL_SOURCE_STATE, &state);  
          
        if (state == AL_STOPPED)  
        {  
            alDeleteSources(1, &player->sourceId);  
            alDeleteBuffers(1, &player->bufferId);  
              
            AArrayList->Remove(destroyList, i);  
            AArrayListAdd(cacheList, player);  
        }  
    }  
}  

因為,我使用了alBufferDataStatic,并且緩存音頻數據,所以這里只是刪除播放器的關聯id,并沒有刪除音頻數據。再次播放同一個音頻的時候繼續使用。OpenAL通常一共只可以申請32個播放器。所以播放器用完還是及時的刪除比較好。

后記

未完,待續,后續更精彩~~~

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內容