Repeating Audio in WatchKit (AVAudioPlayer?)?












1














I am wanting to loop a local audio file in my Apple Watch App. Currently I am using AVAudioPlayerNode and AVAudioEngine which works well but I cannot figure out how to loop the sound.



I noticed that I can use AVAudioPlayer, which has the handy "numberOfLoops" but, for some reason AVAudioPlayer is not working on the watch. I have no idea why.



Here is my current code to play a sound:



_audioPlayer = [[AVAudioPlayerNode alloc] init];
_audioEngine = [[AVAudioEngine alloc] init];
[_audioEngine attachNode:_audioPlayer];

AVAudioFormat *stereoFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2];
[_audioEngine connect:_audioPlayer to:_audioEngine.mainMixerNode format:stereoFormat];

if (!_audioEngine.isRunning) {
NSError* error;
[_audioEngine startAndReturnError:&error];
}

NSError *error;
NSBundle* appBundle = [NSBundle mainBundle];
NSURL *url = [NSURL fileURLWithPath:[appBundle pathForResource:@"FILE_NAME" ofType:@"mp3"]];
AVAudioFile *asset = [[AVAudioFile alloc] initForReading:url error:&error];

[_audioPlayer scheduleFile:asset atTime:nil completionHandler:nil];
[_audioPlayer play];


Here is the code i've tried to use for AVAudioPlayer, but does not work:



NSError *audioError;
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FILE_NAME" ofType:@"mp3"]] error:&audioError];
player.numberOfLoops = MAXFLOAT;
player.delegate = self;
[player play];


I am using WatchKit 5.0(+).










share|improve this question



























    1














    I am wanting to loop a local audio file in my Apple Watch App. Currently I am using AVAudioPlayerNode and AVAudioEngine which works well but I cannot figure out how to loop the sound.



    I noticed that I can use AVAudioPlayer, which has the handy "numberOfLoops" but, for some reason AVAudioPlayer is not working on the watch. I have no idea why.



    Here is my current code to play a sound:



    _audioPlayer = [[AVAudioPlayerNode alloc] init];
    _audioEngine = [[AVAudioEngine alloc] init];
    [_audioEngine attachNode:_audioPlayer];

    AVAudioFormat *stereoFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2];
    [_audioEngine connect:_audioPlayer to:_audioEngine.mainMixerNode format:stereoFormat];

    if (!_audioEngine.isRunning) {
    NSError* error;
    [_audioEngine startAndReturnError:&error];
    }

    NSError *error;
    NSBundle* appBundle = [NSBundle mainBundle];
    NSURL *url = [NSURL fileURLWithPath:[appBundle pathForResource:@"FILE_NAME" ofType:@"mp3"]];
    AVAudioFile *asset = [[AVAudioFile alloc] initForReading:url error:&error];

    [_audioPlayer scheduleFile:asset atTime:nil completionHandler:nil];
    [_audioPlayer play];


    Here is the code i've tried to use for AVAudioPlayer, but does not work:



    NSError *audioError;
    AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FILE_NAME" ofType:@"mp3"]] error:&audioError];
    player.numberOfLoops = MAXFLOAT;
    player.delegate = self;
    [player play];


    I am using WatchKit 5.0(+).










    share|improve this question

























      1












      1








      1


      1





      I am wanting to loop a local audio file in my Apple Watch App. Currently I am using AVAudioPlayerNode and AVAudioEngine which works well but I cannot figure out how to loop the sound.



      I noticed that I can use AVAudioPlayer, which has the handy "numberOfLoops" but, for some reason AVAudioPlayer is not working on the watch. I have no idea why.



      Here is my current code to play a sound:



      _audioPlayer = [[AVAudioPlayerNode alloc] init];
      _audioEngine = [[AVAudioEngine alloc] init];
      [_audioEngine attachNode:_audioPlayer];

      AVAudioFormat *stereoFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2];
      [_audioEngine connect:_audioPlayer to:_audioEngine.mainMixerNode format:stereoFormat];

      if (!_audioEngine.isRunning) {
      NSError* error;
      [_audioEngine startAndReturnError:&error];
      }

      NSError *error;
      NSBundle* appBundle = [NSBundle mainBundle];
      NSURL *url = [NSURL fileURLWithPath:[appBundle pathForResource:@"FILE_NAME" ofType:@"mp3"]];
      AVAudioFile *asset = [[AVAudioFile alloc] initForReading:url error:&error];

      [_audioPlayer scheduleFile:asset atTime:nil completionHandler:nil];
      [_audioPlayer play];


      Here is the code i've tried to use for AVAudioPlayer, but does not work:



      NSError *audioError;
      AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FILE_NAME" ofType:@"mp3"]] error:&audioError];
      player.numberOfLoops = MAXFLOAT;
      player.delegate = self;
      [player play];


      I am using WatchKit 5.0(+).










      share|improve this question













      I am wanting to loop a local audio file in my Apple Watch App. Currently I am using AVAudioPlayerNode and AVAudioEngine which works well but I cannot figure out how to loop the sound.



      I noticed that I can use AVAudioPlayer, which has the handy "numberOfLoops" but, for some reason AVAudioPlayer is not working on the watch. I have no idea why.



      Here is my current code to play a sound:



      _audioPlayer = [[AVAudioPlayerNode alloc] init];
      _audioEngine = [[AVAudioEngine alloc] init];
      [_audioEngine attachNode:_audioPlayer];

      AVAudioFormat *stereoFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2];
      [_audioEngine connect:_audioPlayer to:_audioEngine.mainMixerNode format:stereoFormat];

      if (!_audioEngine.isRunning) {
      NSError* error;
      [_audioEngine startAndReturnError:&error];
      }

      NSError *error;
      NSBundle* appBundle = [NSBundle mainBundle];
      NSURL *url = [NSURL fileURLWithPath:[appBundle pathForResource:@"FILE_NAME" ofType:@"mp3"]];
      AVAudioFile *asset = [[AVAudioFile alloc] initForReading:url error:&error];

      [_audioPlayer scheduleFile:asset atTime:nil completionHandler:nil];
      [_audioPlayer play];


      Here is the code i've tried to use for AVAudioPlayer, but does not work:



      NSError *audioError;
      AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FILE_NAME" ofType:@"mp3"]] error:&audioError];
      player.numberOfLoops = MAXFLOAT;
      player.delegate = self;
      [player play];


      I am using WatchKit 5.0(+).







      watchkit avaudioplayer avaudioengine avaudioplayernode






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 18 '18 at 7:44









      eric

      84




      84
























          2 Answers
          2






          active

          oldest

          votes


















          0














          If your audio file fits into memory, you could schedule playback as an AVAudioBuffer with the AVAudioPlayerNodeBufferLoops option (N.B. only tested on simulator!):



          AVAudioFormat *outputFormat = [_audioPlayer outputFormatForBus:0];

          __block AVAudioPCMBuffer *srcBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:asset.processingFormat frameCapacity:(AVAudioFrameCount)asset.length];

          if (![asset readIntoBuffer:srcBuffer error:&error]) {
          NSLog(@"Read error: %@", error);
          abort();
          }

          AVAudioPCMBuffer *dstBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:outputFormat frameCapacity:(AVAudioFrameCount)asset.length];

          AVAudioConverter *converter = [[AVAudioConverter alloc] initFromFormat:srcBuffer.format toFormat:dstBuffer.format];
          AVAudioConverterOutputStatus status = [converter convertToBuffer:dstBuffer error:&error withInputFromBlock:^AVAudioBuffer * _Nullable(AVAudioPacketCount inNumberOfPackets, AVAudioConverterInputStatus * _Nonnull outStatus) {
          if (srcBuffer) {
          AVAudioBuffer *result = srcBuffer;
          srcBuffer = NULL;
          *outStatus = AVAudioConverterInputStatus_HaveData;
          return result;
          } else {
          *outStatus = AVAudioConverterInputStatus_EndOfStream;
          return NULL;
          }
          }];

          assert(status != AVAudioConverterOutputStatus_Error);

          [_audioPlayer scheduleBuffer:dstBuffer atTime:nil options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
          [_audioPlayer play];





          share|improve this answer





























            1














            You can loop your AVAudioFile by recursively scheduling it:



            __block __weak void (^weakSheduleFile)(void);
            void (^scheduleFile)(void);

            weakSheduleFile = scheduleFile = ^{ [self->_audioPlayer scheduleFile:asset atTime:nil completionHandler:weakSheduleFile]; };

            scheduleFile();


            I'm not sure if this will be a seamless loop. If it's not, you can try always having two files scheduled:



            scheduleFile();
            scheduleFile();





            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53358853%2frepeating-audio-in-watchkit-avaudioplayer%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              If your audio file fits into memory, you could schedule playback as an AVAudioBuffer with the AVAudioPlayerNodeBufferLoops option (N.B. only tested on simulator!):



              AVAudioFormat *outputFormat = [_audioPlayer outputFormatForBus:0];

              __block AVAudioPCMBuffer *srcBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:asset.processingFormat frameCapacity:(AVAudioFrameCount)asset.length];

              if (![asset readIntoBuffer:srcBuffer error:&error]) {
              NSLog(@"Read error: %@", error);
              abort();
              }

              AVAudioPCMBuffer *dstBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:outputFormat frameCapacity:(AVAudioFrameCount)asset.length];

              AVAudioConverter *converter = [[AVAudioConverter alloc] initFromFormat:srcBuffer.format toFormat:dstBuffer.format];
              AVAudioConverterOutputStatus status = [converter convertToBuffer:dstBuffer error:&error withInputFromBlock:^AVAudioBuffer * _Nullable(AVAudioPacketCount inNumberOfPackets, AVAudioConverterInputStatus * _Nonnull outStatus) {
              if (srcBuffer) {
              AVAudioBuffer *result = srcBuffer;
              srcBuffer = NULL;
              *outStatus = AVAudioConverterInputStatus_HaveData;
              return result;
              } else {
              *outStatus = AVAudioConverterInputStatus_EndOfStream;
              return NULL;
              }
              }];

              assert(status != AVAudioConverterOutputStatus_Error);

              [_audioPlayer scheduleBuffer:dstBuffer atTime:nil options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
              [_audioPlayer play];





              share|improve this answer


























                0














                If your audio file fits into memory, you could schedule playback as an AVAudioBuffer with the AVAudioPlayerNodeBufferLoops option (N.B. only tested on simulator!):



                AVAudioFormat *outputFormat = [_audioPlayer outputFormatForBus:0];

                __block AVAudioPCMBuffer *srcBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:asset.processingFormat frameCapacity:(AVAudioFrameCount)asset.length];

                if (![asset readIntoBuffer:srcBuffer error:&error]) {
                NSLog(@"Read error: %@", error);
                abort();
                }

                AVAudioPCMBuffer *dstBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:outputFormat frameCapacity:(AVAudioFrameCount)asset.length];

                AVAudioConverter *converter = [[AVAudioConverter alloc] initFromFormat:srcBuffer.format toFormat:dstBuffer.format];
                AVAudioConverterOutputStatus status = [converter convertToBuffer:dstBuffer error:&error withInputFromBlock:^AVAudioBuffer * _Nullable(AVAudioPacketCount inNumberOfPackets, AVAudioConverterInputStatus * _Nonnull outStatus) {
                if (srcBuffer) {
                AVAudioBuffer *result = srcBuffer;
                srcBuffer = NULL;
                *outStatus = AVAudioConverterInputStatus_HaveData;
                return result;
                } else {
                *outStatus = AVAudioConverterInputStatus_EndOfStream;
                return NULL;
                }
                }];

                assert(status != AVAudioConverterOutputStatus_Error);

                [_audioPlayer scheduleBuffer:dstBuffer atTime:nil options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
                [_audioPlayer play];





                share|improve this answer
























                  0












                  0








                  0






                  If your audio file fits into memory, you could schedule playback as an AVAudioBuffer with the AVAudioPlayerNodeBufferLoops option (N.B. only tested on simulator!):



                  AVAudioFormat *outputFormat = [_audioPlayer outputFormatForBus:0];

                  __block AVAudioPCMBuffer *srcBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:asset.processingFormat frameCapacity:(AVAudioFrameCount)asset.length];

                  if (![asset readIntoBuffer:srcBuffer error:&error]) {
                  NSLog(@"Read error: %@", error);
                  abort();
                  }

                  AVAudioPCMBuffer *dstBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:outputFormat frameCapacity:(AVAudioFrameCount)asset.length];

                  AVAudioConverter *converter = [[AVAudioConverter alloc] initFromFormat:srcBuffer.format toFormat:dstBuffer.format];
                  AVAudioConverterOutputStatus status = [converter convertToBuffer:dstBuffer error:&error withInputFromBlock:^AVAudioBuffer * _Nullable(AVAudioPacketCount inNumberOfPackets, AVAudioConverterInputStatus * _Nonnull outStatus) {
                  if (srcBuffer) {
                  AVAudioBuffer *result = srcBuffer;
                  srcBuffer = NULL;
                  *outStatus = AVAudioConverterInputStatus_HaveData;
                  return result;
                  } else {
                  *outStatus = AVAudioConverterInputStatus_EndOfStream;
                  return NULL;
                  }
                  }];

                  assert(status != AVAudioConverterOutputStatus_Error);

                  [_audioPlayer scheduleBuffer:dstBuffer atTime:nil options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
                  [_audioPlayer play];





                  share|improve this answer












                  If your audio file fits into memory, you could schedule playback as an AVAudioBuffer with the AVAudioPlayerNodeBufferLoops option (N.B. only tested on simulator!):



                  AVAudioFormat *outputFormat = [_audioPlayer outputFormatForBus:0];

                  __block AVAudioPCMBuffer *srcBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:asset.processingFormat frameCapacity:(AVAudioFrameCount)asset.length];

                  if (![asset readIntoBuffer:srcBuffer error:&error]) {
                  NSLog(@"Read error: %@", error);
                  abort();
                  }

                  AVAudioPCMBuffer *dstBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:outputFormat frameCapacity:(AVAudioFrameCount)asset.length];

                  AVAudioConverter *converter = [[AVAudioConverter alloc] initFromFormat:srcBuffer.format toFormat:dstBuffer.format];
                  AVAudioConverterOutputStatus status = [converter convertToBuffer:dstBuffer error:&error withInputFromBlock:^AVAudioBuffer * _Nullable(AVAudioPacketCount inNumberOfPackets, AVAudioConverterInputStatus * _Nonnull outStatus) {
                  if (srcBuffer) {
                  AVAudioBuffer *result = srcBuffer;
                  srcBuffer = NULL;
                  *outStatus = AVAudioConverterInputStatus_HaveData;
                  return result;
                  } else {
                  *outStatus = AVAudioConverterInputStatus_EndOfStream;
                  return NULL;
                  }
                  }];

                  assert(status != AVAudioConverterOutputStatus_Error);

                  [_audioPlayer scheduleBuffer:dstBuffer atTime:nil options:AVAudioPlayerNodeBufferLoops completionHandler:nil];
                  [_audioPlayer play];






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 19 '18 at 13:48









                  Rhythmic Fistman

                  23.8k452105




                  23.8k452105

























                      1














                      You can loop your AVAudioFile by recursively scheduling it:



                      __block __weak void (^weakSheduleFile)(void);
                      void (^scheduleFile)(void);

                      weakSheduleFile = scheduleFile = ^{ [self->_audioPlayer scheduleFile:asset atTime:nil completionHandler:weakSheduleFile]; };

                      scheduleFile();


                      I'm not sure if this will be a seamless loop. If it's not, you can try always having two files scheduled:



                      scheduleFile();
                      scheduleFile();





                      share|improve this answer


























                        1














                        You can loop your AVAudioFile by recursively scheduling it:



                        __block __weak void (^weakSheduleFile)(void);
                        void (^scheduleFile)(void);

                        weakSheduleFile = scheduleFile = ^{ [self->_audioPlayer scheduleFile:asset atTime:nil completionHandler:weakSheduleFile]; };

                        scheduleFile();


                        I'm not sure if this will be a seamless loop. If it's not, you can try always having two files scheduled:



                        scheduleFile();
                        scheduleFile();





                        share|improve this answer
























                          1












                          1








                          1






                          You can loop your AVAudioFile by recursively scheduling it:



                          __block __weak void (^weakSheduleFile)(void);
                          void (^scheduleFile)(void);

                          weakSheduleFile = scheduleFile = ^{ [self->_audioPlayer scheduleFile:asset atTime:nil completionHandler:weakSheduleFile]; };

                          scheduleFile();


                          I'm not sure if this will be a seamless loop. If it's not, you can try always having two files scheduled:



                          scheduleFile();
                          scheduleFile();





                          share|improve this answer












                          You can loop your AVAudioFile by recursively scheduling it:



                          __block __weak void (^weakSheduleFile)(void);
                          void (^scheduleFile)(void);

                          weakSheduleFile = scheduleFile = ^{ [self->_audioPlayer scheduleFile:asset atTime:nil completionHandler:weakSheduleFile]; };

                          scheduleFile();


                          I'm not sure if this will be a seamless loop. If it's not, you can try always having two files scheduled:



                          scheduleFile();
                          scheduleFile();






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 19 '18 at 22:25









                          Rhythmic Fistman

                          23.8k452105




                          23.8k452105






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53358853%2frepeating-audio-in-watchkit-avaudioplayer%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              MongoDB - Not Authorized To Execute Command

                              in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                              Npm cannot find a required file even through it is in the searched directory