In some applications it is necessary to use background music and sound effects, which is implemented in the program.
1. First load the background music needs to use the avfoundation frame
2. Music resources are in the package, so need to get the package path, involving methods-(ID) Initwithcontentsofurl: (nsurl *) URL error: (Nserror *) Outerror;
URL is actually the package address, can be [[nsbundlemainbundle]pathforresource:@] background music "oftype:@" CAF "; Then use Nsurl's Fileurlwithpath method to convert path to URL;
3. Set the number of music plays. Numberofloops. Set to 0 play only once, set to 1 the Loop 1 plays 2 times, set to 1 to play the loop uninterrupted;
4. Set the music sound size. Volume.
5. Prepare to play, call method Preparetoplay.
6. Start playback, call method play; stop playback: stop;
1NSString *path = [[NSBundle mainbundle]pathforresource:@"background Music"OfType:@"CAF"];2Nsurl *url =[Nsurl Fileurlwithpath:path];3Avaudioplayer *player =[[Avaudioplayer Alloc]initwithcontentsofurl:url Error:nil];4Player.numberofloops =-1;5Player.volume =0.5f;6 [player Preparetoplay];7[Player play];
While loading the sound will need to use the Audiotoolbox framework, and music needs to load the package path, using the method is Audioservicescreatesystemsoundid, this is a C language method, where the incoming URL needs to use __ Bridge is converted, and a systemsoundid is sent out to provide playback when called, and the method used for playback is audioservicesplaysystemsound (Systemsoundid insystemsoundid).
1 nsstring *path = [[NSBundle mainbundle]pathforresource:soundfilename Oftype:nil]; 2 Nsurl *url = [Nsurl Fileurlwithpath:path]; 3 Systemsoundid Soundid; 4 audioservicescreatesystemsoundid (__bridge cfurlref) (URL), &soundid); 5 6 audioservicesplaysystemsound (soundid);<br>
There is also a way to Audioservicesplayalertsound, this method will play the sound effects while the vibration, to remind users.
IOS Settings Ringtone---load music and audio and play it