Abdullah Shafique
Abdullah Shafique

Reputation: 6918

iOS Audio Files not playing

I am trying to play my audio file, which is 1.9 seconds, in my iOS App with these lines of code:

NSString *path  = [[NSBundle mainBundle] pathForResource:@"bell" ofType:@"wav"];
NSURL *pathURL = [NSURL fileURLWithPath : path];
SystemSoundID audioEffect;
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);
AudioServicesDisposeSystemSoundID(audioEffect);

The audio file never plays but the code gets called.

file

EDIT: file bell.wav bell.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 48000 Hz

Upvotes: 0

Views: 263

Answers (1)

matt
matt

Reputation: 535925

The problem is that you are disposing the sound before it has a chance to start playing.

My book teaches you how to do this. Here is the code I provide in my book:

void SoundFinished (SystemSoundID snd, void* context) {
    // NSLog(@"finished!");
    AudioServicesRemoveSystemSoundCompletion(snd);
    AudioServicesDisposeSystemSoundID(snd);
}

- (IBAction)doButton:(id)sender {
    NSURL* sndurl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"aif"];
    SystemSoundID snd;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)sndurl, &snd);
    AudioServicesAddSystemSoundCompletion(snd, nil, nil, SoundFinished, nil);
    AudioServicesPlaySystemSound(snd);
}

You can adapt that to use your sound and to trigger the playing in the way you need.

However, do note that you should not be using a 1.9 second sound as a system sound. It is much better to use an AVAudioPlayer (which my book also teaches you to do).

Upvotes: 3

Related Questions