我正在尝试使用以下代码行在我的 iOS 应用程序中播放 1.9 秒的音频文件:
NSString *path = [[NSBundle mainBundle] pathForResource:@"bell" ofType:@"wav"];
NSURL *pathURL = [NSURL fileURLWithPath : path];
SystemSoundID audioEffect;
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);
AudioServicesDisposeSystemSoundID(audioEffect);
音频文件从不播放,但代码被调用。
编辑: 文件 bell.wav
bell.wav:RIFF(小端)数据、WAVE 音频、Microsoft PCM、16 位、立体声 48000 Hz
最佳答案
问题是您在声音有机会开始播放之前就处理掉了它。
我的书教你如何做到这一点。这是我在书中提供的代码:
void SoundFinished (SystemSoundID snd, void* context) {
// NSLog(@"finished!");
AudioServicesRemoveSystemSoundCompletion(snd);
AudioServicesDisposeSystemSoundID(snd);
}
- (IBAction)doButton:(id)sender {
NSURL* sndurl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"aif"];
SystemSoundID snd;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)sndurl, &snd);
AudioServicesAddSystemSoundCompletion(snd, nil, nil, SoundFinished, nil);
AudioServicesPlaySystemSound(snd);
}
您可以调整它以使用您的声音并以您需要的方式触发播放。
但是请注意,您不应将 1.9 秒的声音用作系统声音。最好使用 AVAudioPlayer(我的书也教你这样做)。
关于iOS 音频文件无法播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20830249/