iPhone - 声音无法播放AudioServicesPlaySystemSound或AVAudioPlayer

Oli*_*ver 0 iphone audio camera overlay click

我在UIImagePicker上有一个按钮,我希望它在点击时发出一些声音.为此,我在我的项目资源中有m4a和mp3格式的声音(用于测试目的).

我尝试通过多种方式播放声音,尝试使用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");
}
Run Code Online (Sandbox Code Playgroud)

你能告诉我出了什么问题吗?

Jon*_*pan 6

您不能将MP3与音频服务一起使用.它必须是某个子类型的WAV文件.至于AVAudioPlayer,它支持MP3文件,但是当AVAudioPlayer被释放它停止播放,因为你发送后立即这样做-play(通过发送-release到平衡+alloc),你永远不会听到任何声音.

因此,要么将文件转换为WAV,要么将其挂到AVAudioPlayer足够长的时间以便播放.:)