我正在编写一个 iPhone 应用程序,当发生特定事件时,会播放声音。我尝试使用不同的 WAV、MP3、M4A 文件,但遇到间歇性问题。下面的代码在模拟器中运行良好,但 MP3 无法在 iPhone 上播放。 (如果有的话,3GS)。有任何想法吗?我已将 mp3 文件更改为 wav 文件,它将适用于下面提供的文件 (knock_knock),但不适用于其他文件。可能是它的编码方式?
感谢任何帮助。谢谢
这是代码:
SystemSoundID soundID;
NSString *soundFile;
if (something == somethingelse) {
soundFile = [[NSBundle mainBundle] pathForResource:@"knock_knock" ofType:@"wav"];
}
else {
soundFile = [[NSBundle mainBundle] pathForResource:@"strike" ofType:@"mp3"];
}
AudioServicesCreateSystemSoundID((CFURLRef)
[NSURL fileURLWithPath:soundFile]
, &soundID);
AudioServicesPlaySystemSound(soundID);
最佳答案
系统声音必须未压缩。我遇到了这个问题并更改了代码以使用 AVAudioSession 和 AVAudioPlayer。在我的脑海中,类似这样的东西(需要更好的错误检查)
-(void)load {
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [self path]];
if (fileURL) {
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
[self stop];
self.player = newPlayer;
[newPlayer release];
[self.player prepareToPlay];
}
}
-(void)play {
if (self.player == nil)
[self load];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory: AVAudioSessionCategoryAmbient error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
self.player.currentTime = 0;
[self.player play];
}
关于iPhone 无法使用 type= @"mp3"播放 mp3 声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2111293/