I am testing my app on my 3GS iPhone with iOS 4.2
I am using the following code which plays a sound in my IBAction. It works perfectly in the simulator (both iPad and iPhone) - I hear the sound.
NSString *pathToMusicFile1 = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"mp3"];
NSError *error;
alarmSound = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile1] error:&error];
NSLog(@"Song1 Loaded");
if (alarmSound == nil) {
NSLog(@"Error playing sound");
} else {
alarmSound.numberOfLoops = 20;
alarmSound.volume = 1.0;
[alarmSound play];
}
I have everything declared properly (headers and frameworks etc) as I can hear the sound in the simulator.
I have also checked that my phone is NOT in silent mode!! I hear other sounds from the generic iphone GUI. (example from a datepicker).
I have also cleaned all targets and deleted the app to reinstall.
Any ideas what's wrong?!
It is extremely important to have the "audioPlayer" variable as a property. Otherwise with ARC, it gets released before it gets a chance to play!
It took me half an hour and some googling for this A-ha moment.
My sound works perfectly now!
have you tried
[NSURL URLWithString:pathToMusicFile1];
instead offileURLWithPath:
?My problem was that iOS was autoreleasing my AVAudioPlayer instance before the file got a chance to play. Strangely this only happened with MP3s and not AU files. Solution was to not set it as autorelease and then release it in the delegate method...
...then in the delegate method...
...works great now.
So, I had this issue too - well I'm pretty sure it's the same one...
We've had an app in the app store for a year or so now and recently we needed to change a bit of content although nothing functional.
Suddenly, the sound stopped working - Both the simulator in the latest sdk version (version 4.0) AND on device too (again running iOS 4).
The code that always worked for us was this...
Finally, I found out that you now need to set the type of AVAudioSession playback just to get sound to play through the speaker as it already did! Put following line of code in your app delegate applicationDidFinishLaunching event handler...
Not forgetting to add the include in your app delegate .h file (obviously you need to import AVFoundation framework too if not already done so)...
Hopefully this'll now make your sound play on device.
Don't get cuaght out by what I think might be a separate issue, and that's the sound still doesn't play in the simulator. I've seen other posts suggesting this is the case, but I'm not sure how widespread this is. I found out that if I selected iPad 3.2 as my simulator, it at least worked on that. The joy!
What seems crazy to me is that, surely this must be effecting loads of people and yet it's quite hard to find info or suggestions about something that should be quite a well known issue - after all, I've seen loads of posts on forums that don't seem to have been answered.
Anywayz, hope this helps somebody else.