iOS 语音播放器

@property NSTimeInterval currentTime;//当前播放语音时长
@property(readonly) NSTimeInterval duration; //语音文件总时长
@property float volume;//音量

一、播放录音

- (void)playAmrWithPath:(NSString *)path isLoop:(BOOL)isLoop {
  self.audioPath = path;
  self.isLoop = isLoop;
  NSLog(@"%d", [_player isPlaying]);
  if (_player && _player.isPlaying &&
      [path isEqualToString:_currentMicrotalkId]) {
    _currentTimeInterval = _player.currentTime;
    [_player pause];
    return;
  } else {
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    // 默认情况下扬声器播放
//      _audioSessionCategory = AVAudioSessionCategoryPlayback;
    [[AVAudioSession sharedInstance] setCategory:_audioSessionCategory error:nil];
    
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
      NSData *data = [NSData dataWithContentsOfFile:path];
      if (!data) {
          data = [NSData dataWithContentsOfFile:path];
      }
    _player =
    [[AVAudioPlayer alloc] initWithData:data
                                  error:nil];
    [_player setDelegate:self];
    [_player setVolume:1.0];
    [_player setCurrentTime:0];
    [_player setMeteringEnabled:YES];
    [_player updateMeters];
      
    if ([_player prepareToPlay]) {
      if (_soundTimer == nil) {
        _soundTimer =
        [NSTimer scheduledTimerWithTimeInterval:0.1
                                         target:self
                                       selector:@selector(playProgress)
                                       userInfo:nil
                                        repeats:YES];
      }
      [_player play];
    }
    NSLog(@"___%d", [_player isPlaying]);
  }
}

二、暂停播放

  [_player stop];

三、AVAudioPlayerDelegate代理方法
1⃣️播放完毕

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                       successfully:(BOOL)flag {
//可以在这个方法,做播放完毕后的操作
}

四、
可通过player. currentTime/_player. duration来设置播放进度条

五、AVAudioSession

你可能感兴趣的:(iOS 语音播放器)