QMAudioPlayer.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // QMAudioPlayer.m
  3. // IMSDK-OC
  4. //
  5. // Created by haochongfeng on 2017/8/17.
  6. // Copyright © 2017年 HCF. All rights reserved.
  7. //
  8. #import "QMAudioPlayer.h"
  9. #import "QMAudioAnimation.h"
  10. @implementation QMAudioPlayer
  11. static QMAudioPlayer * instance = nil;
  12. + (QMAudioPlayer *)sharedInstance {
  13. static dispatch_once_t onceToken;
  14. dispatch_once(&onceToken, ^{
  15. instance = [[self alloc] init];
  16. });
  17. return instance;
  18. }
  19. + (id)allocWithZone:(struct _NSZone *)zone {
  20. static dispatch_once_t onceToken;
  21. dispatch_once(&onceToken, ^{
  22. instance = [super allocWithZone:zone];
  23. });
  24. return instance;
  25. }
  26. - (void)startAudioPlayer:(NSString *)fileName withDelegate:(id)audioPlayerDelegate {
  27. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  28. [[AVAudioSession sharedInstance] setActive:YES error:nil];
  29. NSString *playUrl = [NSString stringWithFormat:@"%@/%@/%@",NSHomeDirectory(),@"Documents",fileName];
  30. NSURL *fileURL = [NSURL URLWithString:playUrl];
  31. if (self.player) {
  32. if (self.player.isPlaying == YES && [self.fileName isEqualToString:fileName]) {
  33. [[QMAudioAnimation sharedInstance] stopAudioAnimation];
  34. [self.player stop];
  35. return;
  36. }
  37. }
  38. self.fileName = fileName;
  39. NSError *playError = nil;
  40. AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&playError];
  41. audioPlayer.delegate = audioPlayerDelegate;
  42. [audioPlayer prepareToPlay];
  43. self.player = audioPlayer;
  44. if (playError == nil) {
  45. [self.player play];
  46. }else {
  47. }
  48. }
  49. - (void)stopAudioPlayer {
  50. if (self.player) {
  51. [self.player stop];
  52. self.player = nil;
  53. }
  54. }
  55. - (BOOL)isPlaying:(NSString *)fileName {
  56. if (self.player && [self.fileName isEqualToString:fileName]) {
  57. return self.player.isPlaying;
  58. }else {
  59. return NO;
  60. }
  61. }
  62. @end