AVAudioPlayer is always nill and its isPlaying property is always false. The files are mixed while playing

后端 未结 1 541
天命终不由人
天命终不由人 2021-01-14 23:19

I\'ve been pulling out my hair past three days to fix this problem. I\'ve checked lots of sample codes, read lots of tutorials, and googled and checked lots and lots of ques

相关标签:
1条回答
  • 2021-01-15 00:07

    So... I could finally fix this problem by creating a singleton of the audioplayer. This is how:

    1. First of all, I removed all the code related to the audioPlayer from my NIKMasterViewController class, that includes the audioPlayer declaration and setting it in prepareForSegue.
    2. I created a new class called NIKAudioPlayer.
    3. In NIKAudioPlayer.h:

      #import <Foundation/Foundation.h>
      #import <AVFoundation/AVFoundation.h>
      
      @interface NIKAudioPlayer : NSObject <AVAudioPlayerDelegate>
      {
          AVAudioPlayer *currentPlayer;
      }
      @property (nonatomic, strong) AVAudioPlayer *currentPlayer;
      +(NIKAudioPlayer *) sharedPlayer;
      -(void)playURL:(NSURL*)url;
      @end
      
    4. In NIKAudioPlayer.m:

      #import "NIKAudioPlayer.h"
      
      @implementation NIKAudioPlayer 
      @synthesize currentPlayer;
      
      +(NIKAudioPlayer *) sharedPlayer
      {
          static NIKAudioPlayer* sharedPlayer;
          static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
          sharedPlayer = [[NIKAudioPlayer alloc] init];
          });
          return sharedPlayer;
      }
      
      -(void)playURL:(NSURL*)url
      {
          [currentPlayer stop];
          currentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
          [currentPlayer prepareToPlay];
      }
      
      @end
      
    5. Now in everywhere else in the code (in my case in NIKDetailViewController) whenever I need to play an audio file, I call the sharedPlayer from NIKAudioPlayer:

      [[NIKPlayer sharedPlayer] playURL:audioURL];
      [[NIKPlayer sharedPlayer].currentPlayer prepareToPlay];
      

    To put in a nutshell, replace all audioPlayers in NIKDetailViewController with [NIKPlayer sharedPlayer].currentPlayer, or even cast it and use it everywhere:

    audioPlayer = [NIKPlayer sharedPlayer].currentPlayer

    0 讨论(0)
提交回复
热议问题