萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> ios >> 防止iphone進入休眠後台播放音樂

防止iphone進入休眠後台播放音樂

 步驟一:在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];

copyright © 萬盛學電腦網 all rights reserved