iPhone - Sound not playing with AudioServicesPlaySystemSound nor AVAudioPlayer
I have a button on a UIImagePicker overly , and I want it to make some sound when clicked. To do so, I have in my project resources a sound in m4a and mp3 formats (for test purpose).
I try to play the sound by many ways, trying alternatively with m4a and mp3 formats, but nothing goes out of the iPhone (not the simulator).
The Frameworks are include in the project.
Here is my sample code :
#import <AudioToolBox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
- (IBAction) click:(id)sender {
// Try
/*
SystemSoundID train;
AudioServicesCreateSystemSoundID(CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("TheSound"), CFSTR("mp3"), NULL), &train);
AudioServicesPlaySystemSound(train);
*/
// Try
/*
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: @"TheSound" withExtension: @"mp3"] error:&error];
[audioPlayer play];
[audioPlayer release];
*/
// Try (works)
//AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
// Try
/*
SystemSoundID soundID;
NSURL *开发者_Python百科filePath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"TheSound" ofType:@"mp3"] isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
*/
NSLog(@"Clicked");
}
Could you tell me what is going wrong ?
You can't use an MP3 with Audio Services. It must be a WAV file of a certain subtype. As for AVAudioPlayer
, it supports MP3 files but when AVAudioPlayer
is deallocated it stops playback, and since you do so immediately after sending -play
(by sending -release
to balance the +alloc
), you never hear anything.
So either convert the file to WAV, or hang onto your AVAudioPlayer
long enough for it to play. :)
精彩评论