Play music and sound effects on iOS

Source: Internet
Author: User

1. Play Sound

1.1 First get to audio file path

1 nsstring *path = [[NSBundle mainbundle] Pathforresource:soundfilename Oftype:nil];

1.2 Convert the sound file path to Nsurl

Nsurl *url = [Nsurl Fileurlwithpath:path];

1.3 Load the audio file and return to Systemsoundid (for playing this sound)

systemsoundid soundid;     // The following way is the C language framework, is the audio file processing after the return Systemsoundid assignment to &soundid    Audioservicescreatesystemsoundid (__bridge cfurlref _nonnull) (URL), &soundid);

1.4 Playing sound in the place where you use it

Audioservicesplaysystemsound (Soundid);

2. Play Music

2.1 Get the path to the music file in the package

NSString *path = [[NSBundle mainbundle] Pathforresource:@ " background music " ofType:@ "CAF "];                      NSLog (@ "%@", Path);

2.2 Converting a path to a URL

Nsurl *url = [Nsurl Fileurlwithpath:path];

2.3 Initializing the audio player via a URL

Avaudioplayer *player = [[Avaudioplayer alloc] Initwithcontentsofurl:url Error:nil];

2.4 Set the number of music cycles,-1: Infinite loop playback, 0: Once, 1:2 times ...

[Player setnumberofloops:-1];

2.5 Set the playback volume, can not set

[Player SetVolume:0.5f];

2.6 Setup ready to play

[Player Preparetoplay];

2.7 Plays

[Player play];

Play music and sound effects on iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.