欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS开发 AudioServices(音效播放)的使用

程序员文章站 2022-05-16 20:25:28
一.介绍 audiotoolbox.framework是一套基于c语言的框架,使用它来播放音效其本质是将短音频注册到声音服务(system sound service).system sound s...

一.介绍

audiotoolbox.framework是一套基于c语言的框架,使用它来播放音效其本质是将短音频注册到声音服务(system sound service).system sound service是一种简单、底层的声音播放服务,但是它本身也存在着一些限制:
音频播放时间不能超过30s数据必须是pcm或者ima4格式音频文件必须打包成.caf、.aif、.wav中的一种(注意这是官方文档的说法,实际测试发现一些.mp3也可以播放)

二.使用

使用system sound service 播放音效的步骤如下:

调用audioservicescreatesystemsoundid(cfurlref infileurl, systemsoundid* outsystemsoundid)函数获得系统声音id如果需要监听播放完成操作,则使用audioservicesaddsystemsoundcompletion(systemsoundid insystemsoundid, cfrunloopref inrunloop, cfstringref inrunloopmode, audioservicessystemsoundcompletionproc incompletionroutine, void* inclientdata)方法注册回调函数。调用audioservicesplaysystemsound(systemsoundid insystemsoundid)或者audioservicesplayalertsound(systemsoundid insystemsoundid)方法播放音效(后者带有震动效果)

下面是一个简单的示例程序:

/**
 *  播放完成回调函数
 *
 *  @param soundid    系统声音id
 *  @param clientdata 回调时传递的数据
 */
void soundcompletecallback(systemsoundid soundid,void * clientdata)
{
    nslog(@"播放完成...");
}

/**
 *  播放音效文件
 *
 *  @param name 音频文件名称
 */
- (void)playsoundeffect:(nsstring *)name
{
    nsstring *audiofile = [[nsbundle mainbundle] pathforresource:name oftype:nil];
    nsurl *fileurl = [nsurl fileurlwithpath:audiofile];
    //1.获得系统声音id
    systemsoundid soundid = 0;
    /**
     * infileurl:音频文件url
     * outsystemsoundid:声音id(此函数会将音效文件加入到系统音频服务中并返回一个长整形id)
     */
    audioservicescreatesystemsoundid((__bridge cfurlref)(fileurl), &soundid);
    //如果需要在播放完之后执行某些操作,可以调用如下方法注册一个播放完成回调函数
    audioservicesaddsystemsoundcompletion(soundid, null, null, soundcompletecallback, null);
    //2.播放音频
    audioservicesplaysystemsound(soundid);//播放音效
    //audioservicesplayalertsound(soundid);//播放音效并震动
}