system sound on iphone not playing

2019-05-31 09:17发布

问题:

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?

回答1:

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


回答2:

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);


标签: ios system audio