關於AVAudioPlayer後臺迴圈播放一段本地MP3檔案
阿新 • • 發佈:2019-01-22
@implementation AppDelegate
{
AVAudioPlayer * _player;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 設定支援後臺播放音樂
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory: AVAudioSessionCategoryPlayback error: nil];
[session setActive: YES error: nil];
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"CallEnded" withExtension:@"mp3"];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"applicationDidEnterBackground");
//進入後臺迴圈播放無聲檔案,使其一直在後臺執行
[_player prepareToPlay];
[_player setVolume:1.0];
_player.numberOfLoops = -1; //設定音樂播放次數 -1為一直迴圈
[_player play]; //播放
}
{
AVAudioPlayer * _player;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 設定支援後臺播放音樂
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory: AVAudioSessionCategoryPlayback error: nil];
[session setActive: YES error: nil];
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"CallEnded" withExtension:@"mp3"];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"applicationDidEnterBackground");
//進入後臺迴圈播放無聲檔案,使其一直在後臺執行
[_player prepareToPlay];
[_player setVolume:1.0];
_player.numberOfLoops = -1; //設定音樂播放次數 -1為一直迴圈
[_player play]; //播放
}