ios中音乐后台运行方法

1、引入AVFoundation框架中的#import <AVFoundation/AVFoundation.h>,然后在Info.plist文件中添加UIBackgroundModes键值,它包含一个或多个string的值,选择App plays audio or streams audio/video using AirPlay。

2、在加载音乐的界面ViewDidLoad中添加下面代码

AVAudioSession *session = [AVAudioSession sharedInstance];

[session setActive:YES error:nil];

[session setCategory:AVAudioSessionCategoryPlayback error:nil];


完整代码演示:

- (void)viewDidLoad

{

//音乐在后台播放

AVAudioSession *session = [AVAudioSession sharedInstance];

[session setActive:YES error:nil];

[session setCategory:AVAudioSessionCategoryPlayback error:nil];


NSURL* fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"loop.mp3" ofType:nil]];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];

player.numberOfLoops = -1; // Endless(循环播放)

[player play];


}

你可能感兴趣的:(ios,后台运行,音乐播放)