分享

ios中播放声音和震动

 叹落花 2015-01-18
Objective-c代码  收藏代码
  1. //  
  2. //  AudioUtil.m  
  3. //  iaiai  
  4. // QQ:176291935  
  5. //  
  6. //  Created by iaiai on 14-9-25.  
  7. //  Copyright (c) 2014年 boying. All rights reserved.  
  8. //  
  9.   
  10. #import "AudioUtil.h"  
  11. #import <AudioToolbox/AudioToolbox.h>  
  12.   
  13. @implementation AudioUtil  
  14.   
  15. int number = 0;  
  16.   
  17. /**  
  18.   * 播放声音  
  19.   * @param name 资源名称  
  20.   * @param ext 资源后缀名  
  21.  **/  
  22. -(void)audioPlay:(NSString*)name ext:(NSString*)ext{  
  23.     [self audioPlay:name ext:ext num:1];  
  24. }  
  25.   
  26. /**  
  27.  * 播放声音  
  28.  * @param name 资源名称  
  29.  * @param ext 资源后缀名  
  30.  * @param num 循环次数  
  31.  **/  
  32. -(void)audioPlay:(NSString*)name ext:(NSString*)ext num:(NSInteger*)num{  
  33.     NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:ext];  
  34.     SystemSoundID soundID;  
  35.     AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);  
  36.     AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, audioPlayFinish,num);  
  37.     AudioServicesPlaySystemSound(soundID);  
  38.     number++;  
  39. }  
  40.   
  41. /**  
  42.  * 震动  
  43.  **/  
  44. -(void)vibratePlay{  
  45.     [self vibratePlay:1];  
  46. }  
  47.   
  48. /**  
  49.  * 震动  
  50.  * @param num 震动次数  
  51.  **/  
  52. -(void)vibratePlay:(NSInteger*)num{  
  53.     AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, audioPlayFinish,num);  
  54.     AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  
  55.     number++;  
  56. }  
  57.   
  58. /**  
  59.   * 播放完成之后的回调方法  
  60.   * @param soundID 播放的声音ID  
  61.   * @param num 播放次数  
  62.  **/  
  63. void audioPlayFinish(SystemSoundID soundID,NSInteger* num){  
  64.     if (num&&num>0) {  
  65.         if (number>=num) {  
  66.             if (soundID!=kSystemSoundID_Vibrate) {  
  67.                 AudioServicesDisposeSystemSoundID(soundID);  
  68.             }  
  69.         }else{  
  70.             AudioServicesPlaySystemSound(soundID);  
  71.             number++;  
  72.         }  
  73.     }else{  
  74.         if (soundID!=kSystemSoundID_Vibrate) {  
  75.             AudioServicesDisposeSystemSoundID(soundID);  
  76.         }  
  77.     }  
  78. }  
  79.   
  80. @end  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约