播放简单的声音

Play simple sound

我需要在动作发生时播放声音,我已经有了动作结束时的回调并且工作正常,现在我想给它添加声音。 我添加了 AudioToolbox 作为框架,这是我尝试使用的代码:

SystemSoundID playSoundID;
NSURL *clockSound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"clock" ofType:@"mp3"]];  //the path for my resource
AudioServicesCreateSystemSoundID((__bridge CFURLRef)clockSound, &playSoundID);
AudioServicesPlaySystemSound(playSoundID);

我没有收到任何错误,但没有播放声音

AudioServicesPlaySystemSound()函数无法播放任何MP3文件。该功能仅支持.caf.aac.wav这几种文件格式,并且声音必须在30秒或更短。

Sound files that you play using this function must be: No longer than 30 seconds in duration In linear PCM or IMA4 (IMA/ADPCM) format Packaged in a .caf, .aif, or .wav file

https://developer.apple.com/library/ios/documentation/AudioToolbox/Reference/SystemSoundServicesReference/index.html#//apple_ref/c/func/AudioServicesPlaySystemSound

因此,如果clock.mp3持续时间小于30秒,转换文件格式后可以播放声音。

mp3转换为caf,例如使用afconvert命令,如下所示:

$ afconvert -f caff -d ima4 clock.mp3 clock.caf

如果没有(声音超过30秒),用AVFoundation.frameworkAVPlayer代替。请参阅参议员评论的link。

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL  error:nil];
[player play];

试试这个代码:

NSString *voice=[[NSUserDefaults standardUserDefaults] objectForKey:TB_Voice_conversation_value];

NSError *error;
BOOL Errors;

AVAudioSession *session = [AVAudioSession sharedInstance];
Errors = [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
Errors = [session  overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
[session setActive:YES error:nil];

NSString *path = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],voice];
NSURL *soundUrl = [[NSURL alloc] initFileURLWithPath:path];

_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
if (!Errors)
{
    NSLog(@"Error:%@",error);
}
NSLog(@"session : %@",session);
[_audioPlayer play];