AVAudioPlayer not playing any sound

Objective CAudioXcode4AvfoundationAutomatic Ref-Counting

Objective C Problem Overview


I'm working on an iOS application that needs to play some sounds using the AVFoundation framework. The workspace structure in Xcode 4 contains two projects:

  • Workspace
    • The application itself (main project)
    • A utility library

After building the utility library, it results in a static library which is used in the main application as a framework.

So, when trying to play a sound inside the main application by using the code below, it works as expected.

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *path = [NSString stringWithFormat:@"%@/sound.mp3", resourcePath];

NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url
                                                                    error:&error];
[audioPlayer play];

In contrast, when trying to play exactly the same sound (or any other) inside the utility library using the same code as above, no sound is played at all, even though error is nil and the audioPlayer property values are the right ones (number of channels, duration).

I've made sure the AVFoundation framework is in both projects.

Also, my class uses the AVAudioPlayerDelegate protocol and implements these two methods:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error;

None of these methods is called after trying to play the sound.

If I use the AudioToolbox framework instead, then it plays the sound. But I'm interested in using AVFoundation for several reasons.

Any idea of what is going on? Am I missing something about AVFoundation? Could it be related to using AVAudioPlayer from inside a static library?

Thanks in advance.

Objective C Solutions


Solution 1 - Objective C

I found the solution and it's related to something I didn't mention and didn't think about: I'm compiling with Automatic Reference Counting (ARC).

ARC inserts a release call to the audio player, so it's deallocated right after leaving the method where it is created. It has nothing to do with AVAudioPlayer but with ARC.

In order to solve this issue, I just created an AVAudioPlayer attribute to the class that deals with sounds so that it is not released anymore by ARC. Well, at least, it's not released until the instance of this class is released.

For more information about ARC, refer to Automatic Reference Counting: Zeroing Weak References with details on why I had this issue.

Solution 2 - Objective C

Yes, absolutely; ARC was the reason with my code as well.

I introduced a property:

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

and that made everything work out fine.

Solution 3 - Objective C

use this it will work definitely....

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
                        
NSURL *url = [NSURL fileURLWithPath:@"path of the sound file :)"];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[_player setDelegate:self];
[_player prepareToPlay];
[_player play];

Solution 4 - Objective C

Have you configured the AVAudioSession?

I had a similar problem and fixed it using something like this:

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:NULL];

or

[audioSession setCategory:AVAudioSessionCategoryPlayback error:NULL];

Hope it helps.

Solution 5 - Objective C

Even having audioPlayer var declared in the class scope, it won't play. At least on iOS 10 iPhone 5c physical device.

play() result is true so no errors appear to happen.

Had to add this (Swift 3, 4) and now it plays the sound correctly.

let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)

Solution 6 - Objective C

I have created open source project for simple audio player. Take a look at it if you have any problems with playing audio in iOS (in background too) : https://github.com/wzbozon/DKAudioPlayer

Solution 7 - Objective C

I had the same issue. I had resolved it by adding below line in .h file:

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

And in .m file :

NSError *error;
NSString *soundFilePath = [NSString stringWithFormat:@"%@/dancepechance.mp3",
                               [[NSBundle mainBundle] resourcePath]];
    NSURL *url = [NSURL fileURLWithPath:soundFilePath];
    self.audioPlayer = [[AVAudioPlayer alloc]
                                  initWithContentsOfURL:url
                                  error:&error];
    NSLog(@"Error %@",error);
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];

Solution 8 - Objective C

You can use AVPlayerViewController from AVKit instead for both audio and video. Code is available for both swift and objective c here.

Solution 9 - Objective C

for me this did the job

do {
     try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
    } catch {
        assertionFailure("Failed to configure `AVAAudioSession`: \(error.localizedDescription)")
    }

Solution 10 - Objective C

Please stay on the page for some time, I was facing same issue. and use sleep to resolve it.


NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                             pathForResource:@"sounds-1027-are-you-kidding"
                                             ofType:@"mp3"]];
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
                                      initWithContentsOfURL:url
                                      error:nil];
        [audioPlayer play];
        sleep(2);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmsolerView Question on Stackoverflow
Solution 1 - Objective CmsolerView Answer on Stackoverflow
Solution 2 - Objective CuemView Answer on Stackoverflow
Solution 3 - Objective CAnshulView Answer on Stackoverflow
Solution 4 - Objective CnanoView Answer on Stackoverflow
Solution 5 - Objective CVito ValovView Answer on Stackoverflow
Solution 6 - Objective CDenis KutlubaevView Answer on Stackoverflow
Solution 7 - Objective CPinal PanchaniView Answer on Stackoverflow
Solution 8 - Objective CzeeawanView Answer on Stackoverflow
Solution 9 - Objective CSABYASACHIView Answer on Stackoverflow
Solution 10 - Objective CSumit ShastriView Answer on Stackoverflow