美文网首页
iOS 语音上传 语音录制 上传 播放

iOS 语音上传 语音录制 上传 播放

作者: JumpSmallFlame | 来源:发表于2017-11-16 11:57 被阅读0次

    语音上传 语音录制 上传 播放按钮
    [self.speakBtn addTarget:self action:@selector(speakClick:forEvent:) forControlEvents:UIControlEventAllTouchEvents];

    pragma mark-录音

    • (void)createRecord{
      _recorder = nil;
      NSString * url = NSTemporaryDirectory();
      url = [url stringByAppendingString:[NSString stringWithFormat:@"%f.wav", [[NSDate date] timeIntervalSince1970]]];
      // data = [NSData dataWithContentsOfURL:url];
      NSMutableDictionary * settings = @{}.mutableCopy;
      [settings setObject:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
      [settings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey:AVFormatIDKey];
      [settings setObject:@1 forKey:AVNumberOfChannelsKey];//设置成一个通道,iPnone只有一个麦克风,一个通道已经足够了
      [settings setObject:@16 forKey:AVLinearPCMBitDepthKey];//采样的位数
      self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:url] settings:settings error:nil];
      self.audioRecorder.delegate = self;
      [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
      self.audioRecorder.meteringEnabled = YES;

      BOOL success = [self.audioRecorder record];
      if (success) {
      NSLog(@"录音开始成功");
      }else{
      NSLog(@"录音开始失败");
      }
      // NSMutableDictionary recordSetting = [[NSMutableDictionary alloc]init];
      // //设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
      // [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEGLayer3] forKey:AVFormatIDKey];
      // //设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量)
      // [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
      // //录音通道数 1 或 2
      // [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
      // //线性采样位数 8、16、24、32
      // [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
      // //录音的质量
      // [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
      // NSString
      path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/aaa"];
      // NSURL* url = [NSURL fileURLWithPath:path];
      // data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedAlways error:nil];
      // data = [NSData dataWithContentsOfURL:url];
      // sBase64YuYin = [data base64EncodedStringWithOptions:0];
      //
      // [data writeToFile:[NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp/aaa"] atomically:YES];
      //
      // AVAudioSession *audioSession = [AVAudioSession sharedInstance];
      // NSError *err = nil;
      // [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
      // _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];
      //准备录音
      // [_recorder prepareToRecord];
      // [self beginRecord];

      }

    • (void)playAudioWithURL:(NSURL *)url{
      [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
      NSError * error;
      self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
      self.audioPlayer.delegate = self;
      BOOL success = [self.audioPlayer play];
      if (success) {
      NSLog(@"播放成功");
      }else{
      NSLog(@"播放失败");
      }
      }

    • (void)beginRecord
      {
      NSLog(@"开始录音");
      [self createRecord];
      // [self.recorder record]; // 直接录音, 需要手动停止

      }

    • (void)pauseRecord:(id)sender {
      NSLog(@"暂停录音");
      // [self.recorder pause];
      }

    • (void)stopRecord {
      NSLog(@"停止录音");
      reader = true;
      [self.audioRecorder stop];
      // [self.recorder stop];

     [self.speakBtn setBackgroundImage:[UIImage imageNamed:@"qx10"] forState:UIControlStateNormal];
    

    }
    -(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    URL = recorder.url;
    data = [NSData dataWithContentsOfURL:URL];
    [self update];
    NSLog(@"%@",URL);
    }

    /说话

    • (void)speakClick:(id)sender forEvent:(UIEvent )event{
      if (reader == true) {
      [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
      NSError * error;
      self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:&error];
      self.audioPlayer.delegate = self;
      BOOL success = [self.audioPlayer play];
      if (success) {
      NSLog(@"播放成功");
      }else{
      NSLog(@"播放失败");
      }
      //
      // NSString
      path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/aaa"];
      // NSURL* url = [NSURL fileURLWithPath:path];
      // NSLog(@"%@", url);
      // _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
      // AVAudioSession *audioSession = [AVAudioSession sharedInstance];
      // NSError *err = nil;
      // [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
      // [_player prepareToPlay];
      // [_player play];
      }else{
      UITouchPhase phase = event.allTouches.anyObject.phase;
      if (phase == UITouchPhaseBegan) {
      NSLog(@"press");
      [self createRecord];

        }
        else if(phase == UITouchPhaseEnded){
            NSLog(@"release");
            [self stopRecord];
        } 
      

      }

    }

    pragma mark:上传语音

    -(void)update{
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil ];
    [manager POST:[NSString stringWithFormat:@"http://tyg.youruide.com/app/%@",updateYuYinUrl] parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//这里面没做优化,建议用一个单例
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.mp3", str];//文件名

        [formData appendPartWithFileData:data name:@"audio" fileName:fileName mimeType:@".mp3"];//name:file与服务器对应
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSInteger code = [responseObject [@"code"]integerValue];
        if (code == 200) {
            
            filepath = [[responseObject objectForKey:@"data"] objectForKey:@"filepath"];
            
            [self showSuccessMessage:[responseObject  objectForKey:@"message"]];
            
            
        }
        NSLog(@"上传成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        NSLog(@"上传错误");
    }];
    

    }

    相关文章

      网友评论

          本文标题:iOS 语音上传 语音录制 上传 播放

          本文链接:https://www.haomeiwen.com/subject/uccuhxtx.html