1

I want to play a system sound but I don't hear anything:

- (void) play_system_sound
{
    NSLog(@"Play system sound");

    SystemSoundID soundID;
    NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"];
    NSLog(@"path = %@", path );
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
    AudioServicesPlaySystemSound(soundID);
    AudioServicesDisposeSystemSoundID(soundID);
    NSLog(@"Play system sound DONE");
}

I don't hear anything. What am I doing wrong?

toom
  • 12,864
  • 27
  • 89
  • 128

2 Answers2

5

After AudioServicesPlaySystemSound(soundID) ,don't call AudioServicesDisposeSystemSoundID(soundID) immediately.

Try this :

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
}

-(void)dealloc
{ 
    AudioServicesDisposeSystemSoundID(soundID);
}

- (void)play_system_sound
{
    AudioServicesPlaySystemSound(soundID);
}
Carina
  • 2,260
  • 2
  • 20
  • 45
1

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);
Ben
  • 11
  • 3