Как возобновить обновление просмотров при возобновлении AVAudioplayer - PullRequest
1 голос
/ 02 марта 2012

Я так долго борюсь с этой проблемой, но не могу найти никакого решения для этого

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

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

 -(void)playpauseAction:(id)sender 
{
  if  

  ([audioPlayer isPlaying]){

 [sender setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateSelected];

 [audioPlayer pause];

 [timer invalidate];

  } else {

 [sender setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];

 [audioPlayer play];

 self.timer = [NSTimer scheduledTimerWithTimeInterval:11 target:self selector:@selector(displayviewsAction:) userInfo:nil repeats:NO];
  }  

}

- (void)displayviewsAction:(id)sender

FirstViewController *viewController = [[FirstViewController alloc] init];

viewController.view.frame = CGRectMake(0, 0, 320, 480);

[self.view addSubview:viewController.view];

[self.view addSubview:toolbar];

[viewController release];

self.timer = [NSTimer scheduledTimerWithTimeInterval:23 target:self selector:@selector(secondViewController) userInfo:nil repeats:NO];

-(void)secondViewController {
SecondViewController *secondController = [[SecondViewController alloc] init];

secondController.view.frame = CGRectMake(0, 0, 320, 480);

[self.view addSubview:secondController.view]; 

[self.view addSubview:toolbar];

[secondController release];

self.timer = [NSTimer scheduledTimerWithTimeInterval:27 target:self selector:@selector(ThirdviewController) userInfo:nil repeats:NO];
}

Спасибо и благодарны за ваши ответы и помощь в решении этой проблемы.

1 Ответ

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

Используйте фоновую нить, чтобы привязать вид к плееру, что-то вроде этого:

UIImageView* imageView;   //the view that gets updated

int current_selected_image_index = 0;
float time_for_next_image = 0.0;

AVAudioPlayer* audioPlayer;

NSArray* image_times;   //an array of float values representing each 
                        //time when the view should update

NSArray* image_names;   //an array of the image file names 

-(void)update_view
{
    UIImage* next_image_to_play = [image_names objectAtIndex:current_selected_image_index];
    imageView.image = next_image_to_play;
}

-(void)bind_view_to_audioplayer
{
    while(audioPlayer.isPlaying)
    {
        float currentPlayingTime = (float)audioPlayer.currentTime;
        if(currentPlayingTime >= time_for_next_image)
        {
            current_selected_image_index++;
            [self performSelectorOnMainThread:@selector(update_view) withObject:nil waitUntilDone:NO];
            time_for_next_image = [image_times objectAtIndex:[current_selected_image_index+1)];
        }
        [NSThread sleep:0.2];
    }
}

-(void)init_audio
{
current_selected_image_index = 0;
time_for_next_image = [image_times objectAtIndex:1];
 } 

-(void)play_audio
{
    [audioPlayer play];
    [self performSelectorInBackground:@selector(bind_view_to_audioplayer) withObject:nil];
}

-(void)pause_audio
{
    [audioPlayer pause];
    //that's all, the background thread exits because audioPlayer.isPlaying == NO
    //the value of current_selected_image_index stays where it is, so [self play_audio] picks up 
    //where it left off.
}

также добавьте себя в качестве наблюдателя для уведомления audioPlayerDidFinishPlaying:successfully:, которое будет сброшено после завершения воспроизведения аудиоплеера.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...