kernix
kernix

Reputation: 8490

What Is the Easiest way to Play Sound on the Iphone?

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

Answers (3)

kernix
kernix

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:

  1. Drag mp3 file from finder into XCode project -> Supporting Files. Make sure to copy the file. let's assume the file name is sound.mp3.
  2. Add AVFoundation framework to your project.
  3. import < AVFoundation/AVFoundation.h>

  4. @property (strong) AVAudioPlayer* soundPlayer;
  5. use the following code to init the player and play the mp3: NSURL *chemin = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.mp3", [[NSBundle mainBundle] resourcePath]]]; NSError *error; self.soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:chemin error:&error]; [self.soundPlayer play];

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

Ashwin Kumar
Ashwin Kumar

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

Krumelur
Krumelur

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

Related Questions