2010-11-27 147 views
6

我在这里搜索并尝试了所有不同的解决方案,但没有奏效。所以,让我问:iPhone应用程序 - WAV声音文件不播放

我试图在按下按钮时在iPhone应用程序上播放声音。我进口的音频框架,迷上了该方法的按钮,有被捆绑的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); 

但是,当我按下它不播放声音一个按钮。 (是的,我的声音已打开。)

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

回答

17

首先,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; 
} 
0

我不知道你是否已经解决了这个问题,但对我来说,在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); 
相关问题