SDSoundPlayer.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // SDSoundPlayer.m
  3. // MapDemo
  4. //
  5. // Created by apple on 16/5/19.
  6. // Copyright © 2016年 danson. All rights reserved.
  7. #import "SDSoundPlayer.h"
  8. static SDSoundPlayer *soundplayer = nil;
  9. @implementation SDSoundPlayer
  10. {
  11. NSString *playString;
  12. }
  13. +(SDSoundPlayer *)SDSoundPlayerInit
  14. {
  15. if(soundplayer == nil)
  16. {
  17. soundplayer = [[SDSoundPlayer alloc]init];
  18. [soundplayer setDefaultWithVolume:-1.0 rate:-1.0 pitchMultiplier:-1.0];
  19. }
  20. return soundplayer;
  21. }
  22. //播放声音
  23. -(void)play:(NSString *)string
  24. {
  25. if (myDelegate.myAudioPlayer && ![string containsString:@"您已超速"] && ![playString containsString:@"拍照"]) {
  26. [myDelegate.myAudioPlayer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
  27. myDelegate.myAudioPlayer = nil;
  28. }
  29. playString = string;
  30. if(string && string.length > 0){
  31. AVSpeechSynthesizer *player = [[AVSpeechSynthesizer alloc]init];
  32. AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//设置语音内容
  33. utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//设置语言
  34. utterance.rate = self.rate; //设置语速
  35. utterance.volume = self.volume; //设置音量(0.0~1.0)默认为1.0
  36. utterance.pitchMultiplier = self.pitchMultiplier; //设置语调 (0.5-2.0)
  37. utterance.postUtteranceDelay = 1; //目的是让语音合成器播放下一语句前有短暂的暂停
  38. player.delegate = self;
  39. [player speakUtterance:utterance];
  40. }
  41. }
  42. //初始化配置
  43. /**
  44. * 设置播放的声音参数 如果选择默认请传入 -1.0
  45. *
  46. * @param aVolume 音量(0.0~1.0)默认为1.0
  47. * @param aRate 语速(0.0~1.0)
  48. * @param aPitchMultiplier 语调 (0.5-2.0)
  49. */
  50. -(void)setDefaultWithVolume:(float)aVolume rate:(CGFloat)aRate pitchMultiplier:(CGFloat)aPitchMultiplier
  51. {
  52. self.rate = aRate;
  53. self.volume = aVolume;
  54. self.pitchMultiplier = aPitchMultiplier;
  55. if (aRate == -1.0) {
  56. self.rate = 1;
  57. }
  58. if (aVolume == -1.0) {
  59. self.volume = 1;
  60. }
  61. if (aPitchMultiplier == -1.0) {
  62. self.pitchMultiplier = 1;
  63. }
  64. }
  65. - (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance
  66. {
  67. myDelegate.myAudioPlayer = synthesizer;
  68. }
  69. - (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
  70. {
  71. myDelegate.myAudioPlayer = nil;
  72. }
  73. @end