您的位置:首页 > 其它

音效播放小demo

2015-10-29 20:21 363 查看


音效

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) 方法播放音效(后者带有震动效果)。

#import "ViewController.h"

#import <AudioToolbox/AudioToolbox.h>

@interface
ViewController ()

@end

@implementation ViewController

- (IBAction)star1:(UIButton *)sender {

    

    [self star];

}

- (void)viewDidLoad {

    [super
viewDidLoad];

    

    

    // Do any additional setup after loading the view, typically from a nib.

//    UIPresentationController

//    /Users/waqing/Desktop/Text/Text/ViewController.m:9:9: In file included from /Users/waqing/Desktop/Text/Text/ViewController.m:9:/Users/waqing/Desktop/Text/Text/ViewController.h:9:9: Could not build module 'UIKit'

}

void soundCompleteCallback(SystemSoundID soundID,void * clientData){

    NSLog(@"播放完成...");

}

- (void)star{

    NSString *strPath = [[NSBundle
mainBundle] pathForResource:@"atext.mp3"
ofType:nil];

    NSURL *url = [NSURL
fileURLWithPath:strPath];

    SystemSoundID soundID =
0;

    AudioServicesCreateSystemSoundID((__bridge
CFURLRef)(url), &soundID);

    AudioServicesAddSystemSoundCompletion(soundID,
NULL,
NULL, soundCompleteCallback,
NULL);

    AudioServicesPlayAlertSound(soundID);

//    AudioServicesPlaySystemSound(soundID);

}

- (void)didR
940f
eceiveMemoryWarning {

    [super
didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: