近日做音频播放方面的内容,整理关于音频的东西,发现IOS中有四种种播放音频的方式:
- System Sound Services
- AVAudioPlayer 类
- Audio Queue Services
- OpenAL
1.运用AVAudioPlayer
a.首先导入AVFoundation.framework。
b.创建一个播放器
url 创建
AVAudioPlayer* player = [[AVAudioPlayer alloc]
- initWithContentsOfURL:[NSURL fileURLWithPath:
- [[NSBundle mainBundle]pathForResource:
- @"music" ofType:@"m4a"
- inDirectory:@"/"]]
- error:&err ];//使用本地URL创建
data 创建
- AVAudioPlayer* player = [[AVAudioPlayer alloc]
- initWithData:myData
- error:&err ];//使用NSData创建
1.音量
6.仪表计数
player.meteringEnabled = YES;//开启仪表计数功能
[ player updateMeters];//更新仪表读数
//读取每个声道的平均电平和峰值电平,代表每个声道的分贝数,范围在-100~0之间。
for(int i = 0; i<player.numberOfChannels;i++){
float power = [player averagePowerForChannel:i];
float peak = [player peakPowerForChannel:i]; }
c.播放声音
- [ player prepareToPlay];//分配播放所需的资源,并将其加入内部播放队列
- [player play];//播放
- [player stop];//停止
player.delegate = self;
- - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
- //播放结束时执行的动作
- }
- - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{
- //解码错误执行的动作
- }
- - (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{
- //处理中断的代码
- }
- - (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{
- //处理中断结束的代码
- }
传入 AudioToolbox.framework
a. 播放声音
- - (IBAction)playSystemSound:(id)sender
- {
- NSURL* system_sound_url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
- pathForResource:@"BeepGMC500" ofType:@"wav"]];
- SystemSoundID system_sound_id;
- AudioServicesCreateSystemSoundID(
- (__bridge CFURLRef)system_sound_url,
- &system_sound_id
- );
- // Register the sound completion callback.
- AudioServicesAddSystemSoundCompletion(
- system_sound_id,
- NULL, // uses the main run loop
- NULL, // uses kCFRunLoopDefaultMode
- MySoundFinishedPlayingCallback, // the name of our custom callback function
- NULL // for user data, but we don't need to do that in this case, so we just pass NULL
- );
- // Play the System Sound
- AudioServicesPlaySystemSound(system_sound_id);
- }
- - (IBAction)vibrate:(id)sender
- {
- AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
- }
- void MySoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data)
- {
- AudioServicesDisposeSystemSoundID(sound_id);
- }