1. 程式人生 > >後臺播放音樂,防止iphone進入休眠,超詳細教程(可製作音樂鬧鐘)

後臺播放音樂,防止iphone進入休眠,超詳細教程(可製作音樂鬧鐘)

//  後臺播放音樂

共有4個步驟,一個注意事項

步驟一:在resource資料夾下找到該專案的info.plist新增一個

Required background modes 的陣列

並在下面新增一個元素,其值為

App plays audio

步驟二:

需要匯入相應的framework和標頭檔案

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>


步驟三:

//禁止程式執行時自動鎖屏

        [[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"];      //建立音樂檔案路徑

       NSURL * musicURL= [[NSURLalloc]initFileURLWithPath:musicFilePath];

       AVAudioPlayer * thePlayer  = [[AVAudioPlayeralloc]initWithContentsOfURL:musicURLerror:nil];

        [thePlayerplay];

        [thePlayersetVolume:1];  //設定音量大小

        thePlayer.numberOfLoops = -1;//設定音樂播放次數  -1為一直迴圈

        [musicURLrelease];

        [thePlayerrelease];

注意事項:

注意模擬器是不能展示後臺效果的,不要實現了功能還以為沒實現,請用真機測試

//播一半的歌曲退出後臺後停止

/*MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];

     MPMusicPlaybackState playbackState = musicPlayer.playbackState;

     if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {

     [musicPlayer play];

     } else if (playbackState == MPMusicPlaybackStatePlaying) {

     [musicPlayer pause];

     }*/