iPhone - 声音不能播放AudioServicesPlaySystemSound和AVAudioPlayer
问题描述:
我在UIImagePicker上有一个按钮,我想让它在点击时发出一些声音。 为此,我在我的项目资源中提供了m4a和mp3格式的声音(用于测试目的)。iPhone - 声音不能播放AudioServicesPlaySystemSound和AVAudioPlayer
我尝试以多种方式播放声音,尝试使用m4a和mp3格式,但没有任何东西从iPhone(不是模拟器)中消失。
框架包含在项目中。
这里是我的示例代码:
#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 *filePath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"TheSound" ofType:@"mp3"] isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
*/
NSLog(@"Clicked");
}
你能告诉我是什么问题呢?
答
您不能在音频服务中使用MP3。它必须是某个子类型的WAV文件。至于AVAudioPlayer
,它支持MP3文件,但当AVAudioPlayer
被解除分配时,它会停止播放,并且因为您在发送-play
(通过发送-release
来平衡+alloc
)之后立即这样做,您从未听到任何声音。
因此,无论是将文件转换为WAV,或挂到您的AVAudioPlayer
足够长的时间来播放。 :)
就是这样,非常感谢你 – Oliver 2011-03-12 14:51:01