Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 button. (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.

like image 334
Gabe Riddle Avatar asked Nov 27 '10 23:11

Gabe Riddle


People also ask

Why can't I hear WAV files on iPhone?

WAV stands for Waveform Audio File Format, and it is a file format for audio files within the Windows operating system. Generally, iPhone can't play WAV audio files natively. If you want to play WAV on iPhone the best solution is to convert WAV to iPhone natively supported formats.

Can iOS play WAV files?

Can iPhone play WAV files? The answer is Yes! WAV (Waveform Audio File Format), a file format for audio files in the Windows operating system, is supported by the iOS device and it can read and play WAV files.

Is WAV supported by Apple?

You can choose a different encoding option, including AIFF, Apple Lossless, MP3, and WAV. Music also supports HE-AAC files (also called MPEG-4 AAC files).


1 Answers

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;
}
like image 90
Phil M Avatar answered Sep 29 '22 07:09

Phil M