Play music in the background of iOS

Source: Internet
Author: User

Play music in the background of iOS Blog Category:
    • Ios

http://www.apple.com.cn/developer/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ Audioandvideotechnologies/audioandvideotechnologies.html#//apple_ref/doc/uid/tp40007072-ch19-sw32

1. First import the frame used to play the music in the Project: AV Foundation framework

2. Add code to the project:

Import Frame Header file:

Java code
    1. #Import <AVFoundation/AVFoundation.h>

To define a player variable:

Java code
    1. Avaudioplayer *player;
    2. @property (Strong, nonatomic) Avaudioplayer *player;

To customize the playback method:

Java code
  1. -(void) playsound{
  2. [[Avaudiosession sharedinstance] Setcategory:avaudiosessioncategoryplayback Error:nil];
  3. [[Avaudiosession sharedinstance] Setactive:yes Error:nil];
  4. NSString *soundfilepath =
  5. [[NSBundle Mainbundle] Pathforresource: @"sound" OfType: @"MP3"];
  6. Nsurl *fileurl = [[Nsurl alloc] initfileurlwithpath:soundfilepath];
  7. Self.player = [[Avaudioplayer alloc] Initwithcontentsofurl:fileurl Error:nil];
  8. [FileURL release];
  9. [Player play];
  10. [Player Setdelegate:self];
  11. }

Press the home key to pause playback (APPDELEGATE.M):

Java code
    1. -(void) Applicationdidenterbackground: (uiapplication *) Application
    2. {
    3. if (self.player.playing) {
    4. [Self.player pause];
    5. }
    6. }

Run the software to continue playback (APPDELEGATE.M):

Java code
    1. -(void) Applicationwillenterforeground: (uiapplication *) Application
    2. {
    3. if (self.player.playing = = NO) {
    4. [Self.player play];
    5. }
    6. }
Java code
    1. Simulator can be tested!

Play music in the background of 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.