1. Get the universal short sound ID
#import <Foundation/Foundation.h> @interface mjaudiotool:nsobject/** * Play sound * * @param filename filename */+ (void) PlaySound: (NSString *) filename;/** * destroy sound effects * * @param filename Audio file name */+ (void) Disposesound: (NSString *) filename; @end
#import "MJAudioTool.h" #import <AVFoundation/AVFoundation.h> @implementation mjaudiotool//dictionary: filename as key, Soundid as value//store all audio idstatic nsmutabledictionary *_soundiddict;+ (void) initialize{_soundiddict = [ Nsmutabledictionary dictionary];} + (void) PlaySound: (NSString *) filename{if (!filename) return; 1. Remove Soundid systemsoundid soundid from the dictionary = [_soundiddict[filename] unsignedlongvalue]; if (!soundid) {//create//Load audio file Nsurl *url = [[NSBundle mainbundle] Urlforresource:filename Withextension:ni L]; if (!url) return; Create the sound Effects ID audioservicescreatesystemsoundid ((__bridge cfurlref) URL, &soundid); Put dictionary _soundiddict[filename] = @ (Soundid); }//2. Play Audioservicesplaysystemsound (Soundid);} + (void) Disposesound: (NSString *) filename{if (!filename) return; Systemsoundid Soundid = [_soundiddict[filename] unsignedlongvalue]; if (Soundid) {//Destroy sound ID AuDioservicesdisposesystemsoundid (Soundid); Remove [_soundiddict removeobjectforkey:filename] from the dictionary; }} @end
2. Use of common methods
[Mjaudiotool playsound:@ "Buyao.wav"];
Use of iOS short sound