//
//  GMTelephoneAudioPlay.m
//  Gengmei
//
//  Created by 卢悦明 on 2020/2/23.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMTelephoneAudioPlay.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "NSBundle+GMAILab.h"

@interface GMTelephoneAudioPlay ()
@property (nonatomic, strong) AVAudioPlayer *audioPlay;
@end

@implementation GMTelephoneAudioPlay
- (GMTelephoneAudioPlay *)initWithAudioSource:(NSString *)name ofType:(nonnull NSString *)type{
    self = [super init];
    if (self) {
        NSString *soundPath = [[NSBundle gm_AILabBundle:[self class]] pathForResource:name ofType:type];
        NSURL *soundUrl = [NSURL fileURLWithPath:soundPath ? soundPath : @""];
         //初始化播放器对象
         self.audioPlay = [[AVAudioPlayer alloc]initWithContentsOfURL:soundUrl error:nil];
         //设置声音的大小
         self.audioPlay.volume = 0.5;//范围为（0到1）；
         //设置循环次数，如果为负数，就是无限循环
         self.audioPlay.numberOfLoops =-1;
         //设置播放进度
         self.audioPlay.currentTime = 0;
         //准备播放
         [self.audioPlay prepareToPlay];
    }
    return self;
}


- (void) startAudioPlay {
    self.audioPlay.currentTime = 0;
    [self.audioPlay prepareToPlay];
    [self.audioPlay play];
}

- (void) stopAudioPlay {
    [self.audioPlay pause];
}

- (void)startAudioPlayAndVibration {
    [self startAudioPlay];
    // 开始震动
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, vibrationCompleteCallback, NULL);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

- (void)stopAudioPlayAndVibration {
    [self stopAudioPlay];
    // 停止震动
    AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
    AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
}

void vibrationCompleteCallback(SystemSoundID sound,void * clientData) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(800 * NSEC_PER_MSEC)), dispatch_get_global_queue(0, 0), ^{
           AudioServicesPlaySystemSound(sound);
       });
}

@end
