几种播放音频文件的方式(十二) —— OpenAL框架之基本概览(一)

489 篇文章 14 订阅
464 篇文章 13 订阅

1、版本记录

版本号时间
V1.02017.12.29

2、前言

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框架之基本概览(一)

3、框架基本

3.1 Overview

这个框架在开发文档中是找不到的,但是在xcode中可以看到。下面我们就看一下OpenAL框架的头文件和组成。和其他框架一样,在使用前都需要引入头文件。

#import <OpenAL/OpenAL.h>

openAL框架

/*!
    @file       OpenAL.h
    @framework  OpenAL.framework
    @copyright  (c) 2002-2015 by Apple, Inc., all rights reserved.
    @abstract   Umbrella header for OpenAL framework.
*/
​
#ifndef OpenAL_OpenAL_h
#define OpenAL_OpenAL_h
​
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <OpenAL/oalStaticBufferExtension.h>
#include <OpenAL/oalMacOSX_OALExtensions.h>
​
#endif /* defined(OpenAL_OpenAL_h) */

3.2 OpenAL构成

下面我们就看一下OpenAL的构成。

它由3个实体构成:Listener(听者)、Source(音源)和Buffer(缓存)。

  • Listener :任何可以被Listener“听到”的声音都是来自扬声器。openAL允许你指定Listener相对于Source的位置, 但是本例中我们忽略不计。我们只是针对最基本的静态声音。但是请记住“Listener”的概念,在你处理更复杂的情况时,你可以任意移动此对象。

  • Source:本质上类似与扬声器,它将产生Listener可以“听”到的声音。像Listener一样,你可以通过移动Source来获得groovy位置效应。

  • Buffer: 就是我们播放的声音。它保存原始的音频数据。

3.3 两个重要的对象

  • device(设备):Device实际上是播放声音的硬件。

  • context(环境):是当前所有声音在其中播放的会话(session)。

【学习地址】:FFmpeg/WebRTC/RTMP/NDK/Android音视频流媒体高级开发

【文章福利】:免费领取更多音视频学习资料包、大厂面试题、技术视频和学习路线图,资料包括(C/C++,Linux,FFmpeg webRTC rtmp hls rtsp ffplay srs 等等)有需要的可以点击1079654574加群领取哦~

4、工作过程

  • 获取device

  • context关联到device

  • 将数据放入buffer

  • buffer链接到一个source

  • 播放source

下面我们就详细的看一下大致过程。

获取设备device,并建立一个context

// define these somewhere, like in your .h file  
​
    ALCcontext* mContext;  ALCdevice* mDevice;  
    // start up openAL  
    -(void)initOpenAL  
    {  
        // Initialization   
        mDevice = alcOpenDevice(NULL);
​
        // select the "preferred device"    
        if (mDevice)
        {      
            // use the device to make a context         
            mContext = alcCreateContext(mDevice,NULL);       
            // set my context to the currently active one       
            alcMakeContextCurrent(mContext);   
        }  
    }

将数据存入buffer

//打开音频文件
// get the full path of the file  
  NSString* fileName = [[NSBundle mainBundle] pathForResource:@"neatoEffect" ofType:@"caf"];  
​
  // first, open the file  
  AudioFileID fileID = [self openAudioFile:fileName];
// open the audio file  
// returns a big audio ID struct  
​
- (AudioFileID)openAudioFile:(NSString*)filePath  
{  
    AudioFileID outAFID;   
    // use the NSURl instead of a cfurlref cuz it is easier     
    NSURL * afUrl = [NSURL fileURLWithPath:filePath];
    // do some platform specific stuff..  
#if TARGET_OS_IPHONE    
    OSStatus result = AudioFileOpenURL((CFURLRef)afUrl, kAudioFileReadPermission, 0, &outAFID);  
#else   
    OSStatus result = AudioFileOpenURL((CFURLRef)afUrl, fsRdPerm, 0, &outAFID);  
#endif      
    if (result != 0)
        NSLog(@"cannot openf file: %@",filePath);  
   
    return outAFID;  

从文件中获取实际音频数据。要先计算出有多少数据在文件中

// find out how big the actual audio data is  
    UInt32 fileSize = [self audioFileSize:fileID];
​
/ find the audio portion of the file  
// return the size in bytes  
- (UInt32)audioFileSize:(AudioFileID)fileDescriptor  
{  
    UInt64 outDataSize = 0;    
    UInt32 thePropSize = sizeof(UInt64);   
    OSStatus result = AudioFileGetProperty(fileDescriptor, kAudioFilePropertyAudioDataByteCount, &thePropSize, &outDataSize);  
    if(result != 0)
        NSLog(@"cannot find file size");   
       
    return (UInt32)outDataSize;  
}

这里使用了个函数AudioFileGetProperty(),它用来计算文件中有多少数据并将其放入outDataSize变量。

将数据从文件复制到openAL缓存

// this is where the audio data will live for the moment  
unsigned char * outData = malloc(fileSize);
​
// this where we actually get the bytes from the file and put them  
// into the data buffer  
OSStatus result = noErr;  
result = AudioFileReadBytes(fileID, false, 0, &fileSize, outData);  
AudioFileClose(fileID);   //close the file 
​
if (result != 0)
    NSLog(@"cannot load effect: %@",fileName);  
   
NSUInteger bufferID;  
​
// grab a buffer ID from openAL  
alGenBuffers(1, &bufferID);  
// jam the audio data into the new buffer  
alBufferData(bufferID,AL_FORMAT_STEREO16,outData,fileSize,44100);    // save the buffer so I can release it later  
[bufferStorageArray addObject:[NSNumber numberWithUnsignedInteger:bufferID]];

上面分配一下空间给数据,使用audio toolkit中的AudioFileReadBytes()函数从文件中读取字节到分配好的内存块中。然后调用alGenBuffers()产生一个有 效的bufferID,再调用alBufferData()加载数据块到openAL buffer的缓存中。

如果你是像文章开始介绍的那样使用afconvert命令生成的音频文件,那么你已经知道它们的格式和采样率了。 然而,如果你想要支持各种音频格式和频率, 你最好要构建一个类似于audioFileSize:的方法,但使用kAudioFilePropertyDataFormat获取格式然后转换为适当的 AL_FORMAT,而获得频率可能更复杂些。

将准备好的缓存区连接到source

像缓存一样,我们也需要从openAL获取一个有效的sourceID。一旦我们获得了sourceID我们就可以将source和缓存联系起来 了。最后我们还要进行一些缓存基本设定。如果我们想循环播放,还要设定AL_LOOPING为true。 缺省时,播放是不循环的,所以忽略它就好。然后我将此ID存入到字典数据结构中,以便可以根据名称查找ID。

NSUInteger sourceID;  
// grab a source ID from openAL  
alGenSources(1, &sourceID);  
// attach the buffer to the source  
alSourcei(sourceID, AL_BUFFER, bufferID);  
// set some basic source prefs  
alSourcef(sourceID, AL_PITCH, 1.0f);  
alSourcef(sourceID, AL_GAIN, 1.0f);  
if (loops)
    alSourcei(sourceID, AL_LOOPING, AL_TRUE);  
 
// store this for future use  
[soundDictionary setObject:[NSNumber numberWithUnsignedInt:sourceID] forKey:@"neatoSound"];  
// clean up the buffer  if (outData)  
{  
    free(outData);     
    outData = NULL;  
}

开始播放

// the main method: grab the sound ID from the library  
// and start the source playing  
- (void)playSound:(NSString*)soundKey  
{  
    NSNumber* numVal = [soundDictionary objectForKey:soundKey];    
    if (numVal == nil)
        return;    
   
    NSUInteger sourceID = [numVal unsignedIntValue];   
    alSourcePlay(sourceID);  
}

如果声音不循环,那么它将会自然停止。如果是循环的,你可能需要停止它。

停止播放

- (void)stopSound:(NSString*)soundKey  
{  
    NSNumber* numVal = [soundDictionary objectForKey:soundKey];    
    if (numVal == nil)
        return;    
   
    NSUInteger sourceID = [numVal unsignedIntValue];
    alSourceStop(sourceID);  
}

清除临时内存

-(void)cleanUpOpenAL:(id)sender  
{  
    // delete the sources   
    for (NSNumber* sourceNumber in [soundDictionary allValues])
    {      
        NSUInteger sourceID = [sourceNumber unsignedIntegerValue];         
        alDeleteSources(1, &sourceID);     
    }  
   
    [soundDictionary removeAllObjects];  
    // delete the buffers   
    for (NSNumber* bufferNumber in bufferStorageArray)
    {      
        NSUInteger bufferID = [bufferNumber unsignedIntegerValue];         
        alDeleteBuffers(1, &bufferID);     
    }  
    [bufferStorageArray removeAllObjects];  
   
    // destroy the context      
    alcDestroyContext(mContext);   
    // close the device     
    alcCloseDevice(mDevice);  
}

注意:

在实际应用中你可能有不只一个source(我的每个buffer都有一个source,但我只有8组声音所以不会有什么问题),而可以使用 的source数目是有上限的。

5、参考文章

1. OpenAL系列之一 – iPhone上的OpenAL音频

6、后记

未完,待续~~~

原文链接:几种播放音频文件的方式(十二) —— OpenAL框架之基本概览(一) - 简书

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值