I have an iOS app which is going to provide a sound pad for the user - i.e. when they tap a button a short sound clip is played.
At the moment, the app is designed around using SystemSoundID.
Would it now be advised to use AVAudioPlayer now over this? If so, what would be the ideal code to use? Would it be the standard:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"yoursoundfile"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:nil];
[audioPlayer play];
I found that using AVAudioFoundation should be the easiest way to play an mp3 on objective-c, but I don't know what I'm doing wrong here. No sound on either the device or the simulator. I imported the framework and all the other "normal" things, but it just keep not playing. What is wrong in this code?
NSString *path = [[NSBundle mainBundle] pathForResource:#"DuomoDiFirenze" ofType:#"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio prepareToPlay];
[theAudio play];
Do you compile with ARC? if so make sure to keep a reference to the AVAudioPlayer instance as else ARC will make sure to release it for you and the audio playback will stop immediately.
So when you declare AVAudioPlayer * theAudio as a property of whichever object you are using it it, it will work. That's the only thing you are missing.
I have a soundtrack I would like to play throughout my app even when users change view controllers and such. I have a loop from a soundtrack that I want to repeat once it finishes. I am currently playing sounds through:
NSString *soundFile = [[NSBundle mainBundle]
pathForResource:#"Click03" ofType:#"wav"];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath: soundFile]
error:nil];
[audioPlayer start];
// or [audioPlayer stop];
I am not quite sure if this the best way of playing sounds. Can someone explain to me how to do what I asked above? Thanks in advance!
Basically you are trying to play an background audio..
Check the following links this would help you
Play music in the background using AVAudioplayer
http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/
For repeating audio check this link
How do I repeat a AVAudioPlayer?
Write code to play sound in Appdelegate.
-(void)PlaySound:(NSString*)strSoundFileName
{
fileURL=[[NSURL alloc] initFileURLWithPath:strSoundFileName];
audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
audioPlayer.delegate=self;
[audioPlayer prepareToPlay];
audioPlayer.currentTime=0;
[audioPlayer play];
audioPlayer.numberOfLoops=-1;
}
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.
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.
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.
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];
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.
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)
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
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];
You can use AVPlayerViewController from AVKit instead for both audio and video. Code is available for both swift and objective c here.
for me this did the job
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
} catch {
assertionFailure("Failed to configure `AVAAudioSession`: \(error.localizedDescription)")
}
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);
I got an app wich include several animations. To load these animations i use the MPMoviePlayerController.
The problem is that if the user is currently listening to some music with an app in background mode, the MPMoviePlayerController fade out the music, even if my animation didn't include any sounds.
Here is the code i use to instantiate my player
NSString *moviePath = [[NSBundle mainBundle] pathForResource:#"anim-geoloc" ofType:#"mp4"];
NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
player.repeatMode = MPMovieRepeatModeOne;
player.controlStyle = MPMovieControlStyleNone;
player.movieSourceType = MPMovieSourceTypeFile;
player.shouldAutoplay = YES;
player.useApplicationAudioSession = YES;
[player prepareToPlay];
[movieURL release];
I have tried to change the useApplicationAudioSession attribute but it changes nothing.
How can i play my animation without loosing the music playback ? Is there a better way to perform an animation ?
Thanks
Ok i figured out what's going out. When you use the MPMoviePlayerController and you want to share the audio session with others apps, you must create an audio session like this.
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryAmbient error:NULL];
[session setActive:YES error:NULL];
With this, my animation doesn't stop the iPod app's sound anymore.