防止iphone進(jìn)入休眠后臺播放音樂

字號:


    步驟一:在resource文件夾下找到該項目的info.plist添加一個
    required background modes 的數(shù)組
    并在下面添加一個元素,其值為
    app plays audio
    步驟二:
    需要導(dǎo)入相應(yīng)的framework和頭文件
    #import <audiotoolbox/audiotoolbox.h>
    #import <avfoundation/avfoundation.h>
    步驟三:
    //禁止程序運(yùn)行時自動鎖屏
    [[uiapplicationsharedapplication]setidletimerdisabled:yes];
    步驟四:
    avaudiosession *audiosession = [avaudiosessionsharedinstance];
    nserror *err =nil;
    [audiosession setcategory :avaudiosessioncategoryplayandrecorderror:&err];
    if(err)
    {
    nslog(@audiosession: %@ %d %@, [errdomain], [errcode], [[erruserinfo]description]);
    }
    [audiosessionsetactive:yeserror:&err];
    err =nil;
    if(err)
    {
    nslog(@audiosession: %@ %d %@, [errdomain], [errcode], [[erruserinfo]description]);
    }
    nsstring * musicfilepath = [[nsbundlemainbundle]pathforresource:@初音ミク-world is mine oftype:@mp3]; //創(chuàng)建音樂文件路徑
    nsurl * musicurl= [[nsurlalloc]initfileurlwithpath:musicfilepath];
    avaudioplayer * theplayer = [[avaudioplayeralloc]initwithcontentsofurl:musicurlerror:nil];
    [theplayerplay];
    [theplayersetvolume:1]; //設(shè)置音量大小
    theplayer.numberofloops = -1;//設(shè)置音樂播放次數(shù) -1為一直循環(huán)
    [musicurlrelease];
    [theplayerrelease];