SDSoundPlayer.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. playString = string;
  26. if(string && string.length > 0){
  27. AVSpeechSynthesizer *player = [[AVSpeechSynthesizer alloc]init];
  28. AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//设置语音内容
  29. utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//设置语言
  30. utterance.rate = self.rate; //设置语速
  31. utterance.volume = self.volume; //设置音量(0.0~1.0)默认为1.0
  32. utterance.pitchMultiplier = self.pitchMultiplier; //设置语调 (0.5-2.0)
  33. utterance.postUtteranceDelay = 1; //目的是让语音合成器播放下一语句前有短暂的暂停
  34. player.delegate = self;
  35. [player speakUtterance:utterance];
  36. }
  37. }
  38. //初始化配置
  39. /**
  40. * 设置播放的声音参数 如果选择默认请传入 -1.0
  41. *
  42. * @param aVolume 音量(0.0~1.0)默认为1.0
  43. * @param aRate 语速(0.0~1.0)
  44. * @param aPitchMultiplier 语调 (0.5-2.0)
  45. */
  46. -(void)setDefaultWithVolume:(float)aVolume rate:(CGFloat)aRate pitchMultiplier:(CGFloat)aPitchMultiplier
  47. {
  48. self.rate = aRate;
  49. self.volume = aVolume;
  50. self.pitchMultiplier = aPitchMultiplier;
  51. if (aRate == -1.0) {
  52. self.rate = 1;
  53. }
  54. if (aVolume == -1.0) {
  55. self.volume = 1;
  56. }
  57. if (aPitchMultiplier == -1.0) {
  58. self.pitchMultiplier = 1;
  59. }
  60. }
  61. @end