开发者

iPhone App - WAV sound files don't play

I searched on here and tried out all the different solutions given, but nothing worked. So let me ask:

I'm trying to play a sound on an iPhone app when a button is pressed. I imported the Audio framework, hooked up the button with the method, have the WAV sound file in the bundle, and use the following code to play the sound:

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

But it doesn't play sound when I press a b开发者_如何学Cutton. (Yes, my sound is on.)

Any ideas why this might be, and how I can fix it? I'd be happy to provide any more information if it helps.


First of all, the preferred sound format for iPhone is LE formatted CAF, or mp3 for music. You can convert a wav to caf with the built in terminal utility:

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

Then the easiest away to play a sound is to use the AVAudioPlayer... this quick function can help you load a sound resource:

- (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;
}


I don't know if you have solved the problem, but for me, on iOS 7, sometimes the (__bridge CFURLRef) casting won't work, in which case, if you print out the result of (__bridge CFURLRef)[NSURL fileURLWithPath:path], it will be 0x0. This leads to failure of AudioServicesCreateSystemSoundID(). The return value of the function is type of OSStatus. If it fails, the function will return -50, which means one or more parameters are invalid. (If it executes successfully, it returns 0.)

I solved this by using the C style function getting the path of the file:

    CFBundleRef mainBundle = CFBundleGetMainBundle ();
    CFURLRef soundFileUrl;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜