iOS開發(fā) - 音頻相關(guān)

一、簡介

簡單來說,音頻可以分為 2 種
1.音效

  • 又稱『短音頻』,通常在程序中的播放時(shí)長為 1 ~ 2 s
  • 在應(yīng)用程序中起到點(diǎn)綴效果,提升整體用戶體驗(yàn)

2.音樂

  • 比如游戲中的『背景音樂』,一般播放時(shí)間較長

播放音頻可以使用框架:AVFoundation.framework

二、音效的播放

//1.獲得音效文件的路徑
NSURL *url = [[NSBundle mainBundle] URLForResource:@"aaa.wav" withExtension:nil];
//2.加載音效文件,得到對應(yīng)的音效 ID
SystemSoundID soundID = 0;
AudioServicesCreatessSystemSoundID((__brage CFURLRef)(url)&soundID);
//3.播放音效
AudioServicesPlaySystemSound(soundID);

注意:音效文件只需要加載一次即可,所以可以使用懶加載的方式。

  • 音效播放常見函數(shù)總結(jié)

1.加載音效文件

AudioServicesCreateSystemSoundID((CFURLRef inFileURL, SystemSoundID *outSystemSoundID)

2.釋放音效資源

AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)

3.播放音效

AudioServicesPlaySystemSoundID(SystemSoundID inSystemSoundID)

4.播放音效帶點(diǎn)震動

AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)

三、音效的格式

音效格式

注意:硬件解碼器一次只能對一個(gè)音頻文件解碼。在實(shí)際應(yīng)用中通常使用非壓縮的音頻格式(AIFF)或者 CAF 音頻格式,從而降低系統(tǒng)在音頻解碼時(shí)的消耗,達(dá)到省電的目的。

四、音頻轉(zhuǎn)換工具

  • 轉(zhuǎn)換為 aiff 格式
afconvert -f AIFF -d I8 filename
  • 轉(zhuǎn)換為 caf 格式
afconvert -f caff -d aac -b 32000 filename
  • 批量處理
find .-name '*.mp3' -exec afconvert -f caff -d aac -b 32000 {} \\;

五、音樂的播放

音樂的播放用到一個(gè)叫做 AVAudioPlayer 的類

  • AVAudioPlayer 常用方法如下:
//加載音樂文件
-(id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
-(id)initWithData:(NSData *)data error:(NSError **)outError;
//準(zhǔn)備播放
-(BOOL)prepareToPlay;
//播放(異步播放)
-(BOOL)play;
//暫停
-(void)pause;
//停止
-(void)stop;
//更新測量值
-(void)updateMeters;
//獲得當(dāng)前的平均音量
-(float)averagePowerForChannel:(NSUInteger)channelNumber;
  • 相關(guān)屬性如下:
//是否正在播放
@property(readonly, getter = isPlaying) BOOL playing;
//時(shí)長
@property(readonly) NSTimeInterval duration;
//當(dāng)前的播放位置
@property NSTimeInterval currentTime;
//播放次數(shù)
@property NSInter numberOfLoops;
//音量
@property float volume;
//是否允許更改速率
@property BOOL enableRate;
//播放速率(1 是正常速率,0.5 是一般速率,2 是雙倍速率)
@property float rate;
//有多少個(gè)聲道
@property(readonly) NSUInteger numberOfChannels
//聲道
@property float pan;
//是否允許測量音量
@property(getter = isMeteringEnabled) BOOL meteringEnabled;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容