iPhone App - WAV声音文件无法播放

Gab*_*dle 6 iphone audio ios4 ios

我在这里搜索并尝试了所有不同的解决方案,但没有任何效果.那么让我问一下:

当按下按钮时,我正试图在iPhone应用程序上播放声音.我导入了Audio框架,用方法连接按钮,在包中有WAV声音文件,并使用以下代码播放声音:

    NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"/filename.wav"];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
Run Code Online (Sandbox Code Playgroud)

但按下按钮时它不会发出声音.(是的,我的声音已开启.)

任何想法为什么会这样,以及我如何解决它?如果有帮助,我很乐意提供更多信息.

Phi*_*l M 17

首先,iPhone的首选声音格式是LE格式的CAF,或mp3用于音乐.您可以使用内置的终端实用程序将wav转换为caf:

afconvert -f caff -d LEI16 crash.wav crash.caf
Run Code Online (Sandbox Code Playgroud)

然后最简单的播放声音是使用AVAudioPlayer ...这个快速功能可以帮助您加载声音资源:

- (AVAudioPlayer *) soundNamed:(NSString *)name {
    NSString * path;
    AVAudioPlayer * snd;
    NSError * err;

    path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:name];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSURL * url = [NSURL fileURLWithPath:path];
        snd = [[[AVAudioPlayer alloc] initWithContentsOfURL:url 
                                                      error:&err] autorelease];
        if (! snd) {
            NSLog(@"Sound named '%@' had error %@", name, [err localizedDescription]);
        } else {
            [snd prepareToPlay];
        }
    } else {
        NSLog(@"Sound file '%@' doesn't exist at '%@'", name, path);
    }

    return snd;
}
Run Code Online (Sandbox Code Playgroud)