Repeating Audio playback with AVAudioPlayer

隐身守侯 提交于 2020-05-17 06:29:05

问题


I'm using AVAudioPlayer and want that the user can restart the playback once the loop is played back. For the user feedback I used UIAlertController but I still struggle to get the replay done with AVAudioPlayer. I want that the user can choose replay as often as he like until he choose NO.

Here is my code I have so far, but what to do if the user select YES ... see comment in code below.

    // schedule the audio file
    [self->_playerNode scheduleFile:self->_file atTime:nil completionHandler:^{

          dispatch_async(dispatch_get_main_queue(), ^{

                UIAlertController * alert=   [UIAlertController
                                              alertControllerWithTitle:@"End of file"
                                              message:@"play again?"
                                              preferredStyle:UIAlertControllerStyleAlert];

               UIAlertAction* yes = [UIAlertAction
                                     actionWithTitle:@"YES"
                                     style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction * action)
                                     {

                                            // WHAT TO DO HERE????

                                            [alert dismissViewControllerAnimated:YES completion:nil];
                                     }];

                UIAlertAction* no = [UIAlertAction
                                     actionWithTitle:@"NO"
                                     style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction * action)
                                     {
                                            NSLog(@"Stop");
                                            [self->_engine stop];
                                            [session setActive:false error:nil];
                                            [alert dismissViewControllerAnimated:YES completion:nil];
                                     }];

                [alert addAction:yes];
                [alert addAction:no];

                [self presentViewController:alert animated:YES completion:nil];
            });
        }];

    // playback the audio file
    [self->_playerNode play];

Thanks for your help!


回答1:


As there is no one with any other suggestion I will answer my own question:

I could not find a way to recursivly load the player so I read out the lengths of the file and started a timer:

NSTimeInterval seconds = self->_file.length / SAMPLERATE;

You will also need to handle the case the app goes to background mode and stop + resume the timer!



来源:https://stackoverflow.com/questions/61044213/repeating-audio-playback-with-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!