AVAudioPlayer проблема с паузой - PullRequest
1 голос
/ 14 марта 2012

В моем проекте у меня есть AVAudioPlayer, который воспроизводит песню.После того, как я приостановил его и снова нажал кнопку воспроизведения, он начинается снова, а не в том месте, где я остановился.Почему это происходит?Кроме того, когда я нажимаю кнопку воспроизведения в первый раз, она загружает песню около 3-4 секунд.Я думал, что решил это, загрузив его в другой поток, но он все еще загружается слишком медленно (по крайней мере, представление больше не останавливается).Как я могу это исправить?Вот код:

- (IBAction)play:(id)sender {
  songIsCurrentlyPaused = NO;
  if(songIsCurrentlyPaused==YES){
    [self.background play];
  } else {
    playQueue = dispatch_queue_create("volume_change", NULL);
    dispatch_async(playQueue, ^{ NSString *filePath = 
      [[NSBundle mainBundle]pathForResource:@"some_song" ofType:@"mp3"];
      NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
      self.background = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
      self.background.delegate = self;
      [self.background setNumberOfLoops:1];
      [self.background setVolume:0.5];
      [self.background play]; });

      [trackNameLabel setText:@"Currently playing :\n some_song"];
      self.timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(updateProgressBar) userInfo:nil repeats:YES];
    }
}

- (IBAction)pause:(id)sender {
  songIsCurrentlyPaused = YES;
  [self.background pause];
  [trackNameLabel setText:@"Currently playing : some_song (paused)"];
  [self.progressBar setProgress:self.background.currentTime/self.background.duration animated:YES];
}

Спасибо!

1 Ответ

1 голос
/ 14 марта 2012

Вы устанавливаете songIsCurrentlyPaused на NO в начале play:

Попробуйте прокомментировать это:

- (IBAction)play:(id)sender {
  //songIsCurrentlyPaused = NO;
  if(songIsCurrentlyPaused==YES){
    [self.background play];
  } else {
    playQueue = dispatch_queue_create("volume_change", NULL);
    dispatch_async(playQueue, ^{ NSString *filePath = 
      [[NSBundle mainBundle]pathForResource:@"some_song" ofType:@"mp3"];
      NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
      self.background = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
      self.background.delegate = self;
      [self.background setNumberOfLoops:1];
      [self.background setVolume:0.5];
      [self.background play]; });

      [trackNameLabel setText:@"Currently playing :\n some_song"];
      self.timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(updateProgressBar) userInfo:nil repeats:YES];
    }
}

- (IBAction)pause:(id)sender {
  songIsCurrentlyPaused = YES;
  [self.background pause];
  [trackNameLabel setText:@"Currently playing : some_song (paused)"];
  [self.progressBar setProgress:self.background.currentTime/self.background.duration animated:YES];
}

Если вы хотите избавиться от этой начальной паузы, вам придется полностью реорганизовать настройки своего игрока. Инициализируйте его, прежде чем пользователь сможет нажать кнопку воспроизведения, а также позвоните:

[self.background prepareToPlay];

, который будет предварительно загружать песню. Также переместите songIsCurrentlyPaused = NO; в более раннее место в коде.

EDIT:

Чтобы избавиться от начальной задержки, вы должны переместить инициализирующий код куда-нибудь, например loadView или viweDidLoad.

   //initialization code
   NSString *filePath = [[NSBundle mainBundle]pathForResource:@"some_song" ofType:@"mp3"];
   NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
   self.background = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
   self.background.delegate = self;
   [self.background setNumberOfLoops:1];
   [self.background setVolume:0.5];
   [self.background prepareToPlay];

Теперь это может вызвать задержку в отображении пользовательского интерфейса, поэтому вы можете не рассматривать предварительную загрузку данных. в фоновом потоке.

Ваши IBAction методы должны быть изменены:

- (IBAction)play:(id)sender
{

   if (songIsCurrentlyPaused==YES) 
   { 
      [self.background play];
   }
   else
   {
      playQueue = dispatch_queue_create("volume_change", NULL);
      dispatch_async(playQueue, ^{
         [self.background setCurrentTime: 0.0];
         [self.background play];
      });

      [self.progressBar setProgress:0.0 animated:YES];
      [trackNameLabel setText:@"Currently playing :\n some_song"];
      self.timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(updateProgressBar) userInfo:nil repeats:YES];

  }
  songIsCurrentlyPaused = NO;
}

- (IBAction)pause:(id)sender
{
  songIsCurrentlyPaused = YES;
  [self.background pause];
  [trackNameLabel setText:@"Currently playing : some_song (paused)"];
  [self.progressBar setProgress:self.background.currentTime/self.background.duration animated:YES];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...