AVAudioPlayer does not play audio once every 15 times

I am facing a really strange problem with AVAudioPlayer. I have initialized AVAudioPlayer as below. It plays sound most of the time, but the sound doesn't play once every 15-20 times. The player gets the correct initialization and there are no errors. Please help me fix the problem.

AVAudioPlayer *backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
self.backgroundMusicPlayer = backgroundMusicPlayer;
[backgroundMusicPlayer release];
[self.backgroundMusicPlayer setDelegate:self];
[self.backgroundMusicPlayer prepareToPlay];
[self.backgroundMusicPlayer play];

      

+3


source to share


1 answer


Use GCD to load audio data

. using GCD to asynchronously load the song data into an NSData instance and use that as a channel for the audio player. you have to do this because loading the audio file data, depending on the length of the audio file, can take a long time and if you do it on the main stream then you run the risk of frustrating the UI experience. Because of this, you need to use a global parallel queue to make sure your code doesn't run on the main thread. If it is on the main thread then the problem is how you go. see this example code

     dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(dispatchQueue, ^(void)
     { 
    NSBundle *mainBundle = [NSBundle mainBundle];
        NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"];
        NSData *fileData = [NSData dataWithContentsOfFile:filePath]; NSError *audioPlayerError = nil;
     self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&audioPlayerError];

        if (self.audioPlayer != nil)
    {
        self.audioPlayer.delegate = self;
        if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play])
    {
        NSLog(@"Successfully started playing.");
        } 
    else 
    { 
    NSLog(@"Failed to play the audio file.");
     self.audioPlayer = nil;
        }
        } 
    else { NSLog(@"Could not instantiate the audio player.");
} });

      



Your problem may also be due to initWithContentsOfURL

if it doesn't receive data via that url then it won't play audio.

Another problem with your code might be freeing the audioPlayer object. If you allocate a lot of objects and never free them from memory. This can eventually lead to low memory.

+3


source







All Articles