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