iOS开发项目- 基于WebSocket的聊天通讯(2)

2020-01-18 17:12:19王旭

长按录音,松开停止


- (void)setClikeSpaceState:(NSString *)aState
{
  NSLog(@"点击语音---");  

  if([aState isEqualToString:@"begin"])
  {
    NSLog(@"begin---");

    dateName = [self convertDateFromString];
    //创建录音文件保存路径
    NSURL *url=[self getPlayPath:dateName];
    //创建录音格式设置
    NSDictionary *setting=[self getAudioSetting];
    //创建录音机
    NSError *error=nil;
    _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
    _audioRecorder.delegate=self;
    _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES

    if (![self.audioRecorder isRecording]) {
      [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
      //    self.timer.fireDate=[NSDate distantPast];

      NSLog(@"111");
    }


  }else
  {
    NSLog(@"end---");


    /** 停止录音*/
    [self.audioRecorder stop];


    /** 录音地址*/
    NSURL *url = [self getPlayPath:dateName];

    /** 加载数据*/

    AVAudioPlayer  *audioPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    Model *model = [[Model alloc]init];
    model.duration = [NSString stringWithFormat:@"%.f",audioPlayer1.duration];
    model.spacePath = dateName;



    /** table 刷新*/
    [self.spaceData addObject:model];
    [self.table reloadData];


    /** table 滚动到当前row*/

    [self.table selectRowAtIndexPath:[NSIndexPath indexPathForRow:(self.spaceData.count - 1) inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];






  }
}

点击table 播放


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


  Model *model = self.spaceData[indexPath.row];  

  /** 播放录音*/
  NSURL *url=[self getPlayPath:model.spacePath];
  NSError *error=nil;
  _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
  _audioPlayer.numberOfLoops=0;

  [_audioPlayer prepareToPlay];
  [self.audioPlayer play];

  NSLog(@"%.0f---aaaa",_audioPlayer.duration);

  /** UIImage动画数组*/
  NSMutableArray  *imgData = [NSMutableArray array];
  for(int i=0;i<4;i++)
  {
    UIImage *aImage = [UIImage imageNamed:[NSString stringWithFormat:@"chat_receiver_audio_playing00%d",i]];
    [imgData addObject:aImage];

  }

  TwoTableViewCell *twoCell = [self.table cellForRowAtIndexPath:indexPath];




  /** 点击动画*/

  [twoCell.speak setAnimationImages:imgData];
  //    [twoCell.speak setAnimationRepeatCount:1];
  [twoCell.speak setAnimationDuration:1];
  [twoCell.speak startAnimating];

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([model.duration intValue] * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    [twoCell.speak stopAnimating];

  });

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。