Reputation: 8490
What Is the Easiest way to Play Sound on the Iphone? I have an mp3 file, I'd rather keep it and not convert it to other format.
Upvotes: 0
Views: 114
Reputation: 8490
Apparently this turned out to be quite a mess, but I found a solution. I'm running XCode 4.4.1.
Here are the steps that worked for me:
Now at this point, I got an exception which is described here: AVFoundation iOS 5 In short it means that there is probably a bug in the simulator which shouldn't happen on the device. In my case I turned all exception on, which stopped my code from executing. What you should do is to remove the option of throwing all exceptions.
In addition, in my case it's 3-5 seconds until it first play the sound, so be patient when you don't get the sound right away. After it play for the first time, it will play instantly.
Upvotes: 0
Reputation: 622
First add AVFoundation Framework to the project [Goto Target> Right click on project>Build Phases>Link Binary with Library> Click on +> select AVFoundation> Add]
// get file path
NSString *soundPath = [[NSBundle mainBundle] pathForResource: fileNameToPlay ofType:@"mp3"];
// allocate and refer to file
AVAudioPlayer *player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: soundPath] error: NULL];
// set delegate
player. delegate = self;
// play
[player play];
Upvotes: 1
Reputation: 32577
The simplest way I know of to play an MP3 file is to use the AVAudioPlayer
class. Basically, just do (skipping error checking, setting delegate for detecting completion, etc):
NSURL* soundUrl = [[NSBundle mainBundle] URLForResource:@"soundFile" withExtension:@"mp3"];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&err];
[player play];
Upvotes: 3