当前位置: 代码迷 >> 综合 >> iOS音频——使用System Sound API
  详细解决方案

iOS音频——使用System Sound API

热度:71   发布时间:2024-01-04 21:52:52.0

是C语言的低层次API,可以播放短的声音,不能暂停或停止等控制。

可以用来制作游戏音效和操作音,以及提醒用户要做某件事,还可以发出振动提醒,但是只能在iphone设备上。

播放系统声音

主要用于游戏音效和操作声音等。

#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>@interface ViewController ()- (IBAction)playSystemSound:(id)sender;@end#pragma mark -定义一个回调函数,用于当声音播放完成之后回调
void SoundFinishedPlayingCallback(SystemSoundID sound_id, void * user_data)
{//注销声音播放完成事件回调函数AudioServicesRemoveSystemSoundCompletion(sound_id);//释放SystemSoundIDAudioServicesDisposeSystemSoundID(sound_id);
}@implementation ViewController- (void)viewDidLoad
{[super viewDidLoad];
}- (IBAction)playSystemSound:(id)sender
{NSString *path = [[NSBundle mainBundle] pathForResource:@"AlertChordStroke" ofType:@"wav"];NSURL *system_sound_url = [NSURL fileURLWithPath:path];SystemSoundID system_sound_id;//创建SystemSoundIDAudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);//注销声音播放完成事件回调函数AudioServicesAddSystemSoundCompletion(system_sound_id, NULL, NULL, SoundFinishedPlayingCallback, NULL);//播放系统声音AudioServicesPlaySystemSound(system_sound_id);
}@end

发出警告提醒

只在iphone下有振动。

- (IBAction)alertSound:(id)sender
{NSURL *system_sound_url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"AlertChordStroke" ofType:@"wav"]];SystemSoundID system_sound_id;AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);AudioServicesAddSystemSoundCompletion(system_sound_id, NULL, NULL, SoundFinishedPlayingCallback, NULL);AudioServicesPlayAlertSound(system_sound_id);
}

振动

- (IBAction)vibrate:(id)sender
{NSString *deviceModel = [[UIDevice currentDevice] model];if ([deviceModel isEqualToString:@"iPhone"]){AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);}else{UIAlertController *alertC = [[UIAlertController alloc] init];[alertC setTitle:@"提示"];UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"设备不支持" style:UIAlertActionStyleDefault handler:nil];[alertC addAction:alertAction];[self presentViewController:alertC animated:YES completion:nil];}
}

 

  相关解决方案