【问题标题】:iPhone App - WAV sound files don't playiPhone App - WAV 声音文件无法播放
【发布时间】:2010-11-27 23:13:08
【问题描述】:

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

我正在尝试在按下按钮时在 iPhone 应用上播放声音。我导入了 Audio 框架,用方法连接了按钮,在 bundle 中有 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);

但是当我按下按钮时它不会播放声音。 (是的,我的声音是开着的。)

知道为什么会这样,我该如何解决?如果有帮助,我很乐意提供更多信息。

【问题讨论】:

    标签: iphone ios ios4 audio


    【解决方案1】:

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

    afconvert -f caff -d LEI16 crash.wav crash.caf
    

    那么播放声音最简单的方法就是使用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;
    }
    

    【讨论】:

      【解决方案2】:

      我不知道你是否解决了这个问题,但对我来说,在 iOS 7 上,有时(__bridge CFURLRef) 转换不起作用,在这种情况下,如果你打印出(__bridge CFURLRef)[NSURL fileURLWithPath:path] 的结果,它将是0x0。这会导致AudioServicesCreateSystemSoundID() 失败。该函数的返回值为OSStatus 类型。如果失败,函数将返回-50,表示一个或多个参数无效。 (如果执行成功,则返回0。)

      我通过使用 C 样式函数获取文件路径解决了这个问题:

          CFBundleRef mainBundle = CFBundleGetMainBundle ();
          CFURLRef soundFileUrl;
      
          soundFileUrl = CFBundleCopyResourceURL(mainBundle, CFSTR("fileName"), CFSTR("wav"), NULL);
          AudioServicesCreateSystemSoundID(soundFileUrl, &soundID);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多