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.
Please stay on the page for some time, I was facing same issue. and use sleep to resolve it.
Have you configured the AVAudioSession?
I had a similar problem and fixed it using something like this:
or
Hope it helps.
Yes, absolutely; ARC was the reason with my code as well.
I introduced a property:
and that made everything work out fine.
Even having audioPlayer var declared in the class scope, it won't play. At least on iOS 10 iPhone 5c physical device.
play()
result istrue
so no errors appear to happen.Had to add this (Swift 3, 4) and now it plays the sound correctly.
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
use this it will work definitely....