首页 > 学院 > 开发设计 > 正文

UI音乐播放之入门篇AudioSerVicesPlay

2019-11-14 18:30:32
字体:
来源:转载
供稿:网友

-1-  AuidoSerVices 常用于提示音的播放,该种音频具有以下四种特点:

      1>长度一般不超过30秒,不需要对播放过程进行控制

      2>不能循环播放,不能暂停

      3>不能播放立体声

      4>不能播放混音

-2-创建提示音频AuidoSerVices。。的准备工作

 1.添加一个系统类库。audioToolbox.framework

 2.导入头文件在viewController中 #import <AudioToolbox/AudioToolbox.h>

 

 

-3-提示音的几个常用方法:

1.获得音效文件的路径

   NSURL *url = [[NSBundle mainBundle] URLForResource:@"m_03.wav" withExtension:nil];

2.加载音效文件,得到对应的音效ID

   SystemSoundID soundID = 0;

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

3.播放音效

   AudioServicesPlaySystemSound(soundID);

 4.音效播放的c语言函数 

 音效播放的函数都是基于c语言编写的,所以在使用的过程中要注意与oc方法使用的区别

加载音效文件

  AudioServicesCreateSystemSoundID(CFURLRef inFileURL, SystemSoundID *outSystemSoundID)

释放音效资源

  AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)

播放音效

  AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)

播放音效带点震动

  AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)

 

-4-程序简单实现

#import "RootViewController.h"#import <AudioToolbox/AudioToolbox.h>@interface RootViewController ()@end@implementation RootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization    }    return self;}- (void)viewDidLoad{    [super viewDidLoad];    [self creatUIButton];}-(void)creatUIButton{    UIButton * btn=[UIButton buttonWithType:UIButtonTypeCustom];     btn.frame=CGRectMake(100, 100, 100, 100);    btn.backgroundColor=[UIColor grayColor];    [btn setTitle:@"播放" forState:UIControlStateNormal];    [btn setTitleColor:[UIColor cyanColor ] forState:UIControlStateNormal];    [btn addTarget:self action:@selector(PRessBtn:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:btn];}-(void)pressBtn:(id)sender{    //1.获取全路径 因为加载音效需要使用CFURLRef 来加载音乐,所以使用能和它相互转换的NSURL 来转换路径    NSString * pathStr= [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"wav"];    NSURL * url=[NSURL fileURLWithPath:pathStr];        //2.创建音效ID 一个ID代表一个音效文件    SystemSoundID SID;    //3.将音乐文件与ID绑定   将url 强转 将sid与之绑定    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &SID);    //4.播放音效    AudioServicesPlayAlertSound(SID);    //5.当我们需要在音效播放结束时取消该音效则需要使用以下方法 函数名固定    AudioServicesAddSystemSoundCompletion(SID, nil, nil,finishSound, nil);}//该函数为系统方法,函数名,参数固定,不能修改void finishSound(SystemSoundID SID,void * finish){  //6.撤销SID    AudioServicesDisposeSystemSoundID(SID);}

注意:点击播放,就可以播放音效文件

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表