今天做ios 添加音效的效果,简单记录一下实现方法,音效主要指的是一些短音频播放,通常作为点缀音频,就比如微信摇一摇中的音效。
我们使用时需要引入AudioToolbox.framework这个框架,使用它来播放音效本质上是将短音频注册到系统声音服务(System Sound Service)。System Sound Service是一种简单、底层的声音播放服务,但是它本身也存在着一些限制:
1、播放时间不能超过30s
2、音频文件必须为.caf、.aif、.wav中的一种
下面是一个简单的小例子
//
// ViewController.m
// TestWeChatSounds
//
// Created by mifeng on 16/3/1.
// Copyright © 2016年 mifeng. All rights reserved.
//
#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)play:(id)sender {
[self playSoundEffect:@"shakeChecking.wav"];
}
- (void)playSoundEffect:(NSString *)name{
NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:nil];
NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
// NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"m_10.wav" withExtension:nil];
//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);//播放音效并震动
}
void soundCompleteCallback(SystemSoundID soundID,void * clientData){
NSLog(@"播放完成...");
}
参考文章:
http://www.cnblogs.com/oumygade/p/4166504.html