5

I'm trying to get a sound to play but when I code:

AudioServicesCreateSystemSoundID ((CFURLRef) alertSound, &soundFileObject);

it throws the following error:

Cast of Objective-C pointer type 'NSURL *' to C pointer type 'CFURLRef' (aka 'const struct __CFURL *') requires a bridged cast error

I have tried both of the two following suggested solutions:

AudioServicesCreateSystemSoundID ((__bridge CFURLRef) alertSound, &soundFileObject);

or

AudioServicesCreateSystemSoundID ((CFURLRef) CFBridgingRetain(alertSound), &soundFileObject);

But I still can't get the sound to play.

I guess the question is: is the bridging error the cause of the sound not playing, or should I be looking else where?

I can get the sound to play using the SysSound sample code and I'm using iOS 6 and Xcode 4.5.

Thanks for any pointers :)

robspencer77
  • 149
  • 2
  • 11

1 Answers1

10

The cast is probably not the reason the sound is not playing:

AudioServicesCreateSystemSoundID ((__bridge CFURLRef) alertSound, &soundFileObject);

is fine.

Most likely your error is in code that you have not shown us. A common problem is an error in the URL creation or an invalid file format.

Modify your code as follows:

OSStatus status = AudioServicesCreateSystemSoundID((__bridge CFURLRef)alertSound, &soundFileObject);
NSLog(@"AudioServicesCreateSystemSoundID status = %ld", status);

and check what status code you get; parmErr (-50) is relatively common and usually means your URL is nil.

Oh, and one more thought, you don't show where you're actually playing the sound. You do know that AudioServicesCreateSystemSoundID does not actually play the sound. You need to call:

AudioServicesPlaySystemSound(soundFileObject);

Apologies if you knew that already!

idz
  • 12,825
  • 1
  • 29
  • 40
  • Yep, -50. My NSURL looks like this: NSURL *alertSound = [[NSBundle mainBundle] URLForResource: @"tap" withExtension: @"aif"]; And the file "tap.aif" is located in a group I created called Sounds. Is there somewhere specific that it needs to be placed? Many thanks for your help! – robspencer77 Jul 28 '12 at 20:06
  • Just to be sure check in the debugger or with an `NSLog` that the URL is indeed nil. This would mean that (as I think you are beginning to suspect) that Xcode is not copying your sound into your app's bundle. You could try removing it (reference only!!!!) from you project and re-adding it and also double checking that the spelling of the file name is correct (could it be .aiff ?). I don't think you need to put it anywhere special. I usually put such things in the "Supporting Files" group that Xcode creates, but I do not think that is required. – idz Jul 28 '12 at 20:21
  • Ah, got it! Thanks! :) Not sure why that hadn't added properly in the first place. Cheers, idz! – robspencer77 Jul 28 '12 at 20:27