Best ways to play simple sound effect in iOS

前端 未结 5 578
野性不改
野性不改 2020-11-30 01:54

I\'m finding a number of conflicting data about playing sounds in iOS. What is a recommended way to play just a simple \"ping\" sound bite every time the user touches the sc

5条回答
  •  情深已故
    2020-11-30 02:53

    (Small amendment to the correct answer to take care of the disposing of the audio)

    NSString *path  = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"];
    NSURL *pathURL = [NSURL fileURLWithPath : path];
    
    SystemSoundID audioEffect;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
    AudioServicesPlaySystemSound(audioEffect);
    // Using GCD, we can use a block to dispose of the audio effect without using a NSTimer or something else to figure out when it'll be finished playing.
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AudioServicesDisposeSystemSoundID(audioEffect);
    });
    

提交回复
热议问题