感谢大家关注,自己找到问题的原因了。
虚拟器不支持按下"Home"后继续播放,真机Ok!
在按下设备的 “home”键后,程序在后台运行,希望继续播放乐曲。
各位老大帮看看我哪里做错了?
或缺少什么代码?谢谢。
我已经进行了如下设置:
在程序启动时
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//后台运行音乐的尝试
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
backgroundSupported = device.multitaskingSupported;
NSLog(@\"backgroundSupported[%@]\",backgroundSupported ? @\"YES\" : @\"NO\");
[[AVAudioSession sharedInstance] setDelegate:self];
NSError *audioSessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError];
if (audioSessionError)
NSLog(@\"Error setting audio category: %@\", [audioSessionError localizedDescription]);
[[AVAudioSession sharedInstance] setActive:YES error:&audioSessionError];
if (audioSessionError)
NSLog(@\"Error setting audio active: %@\", [audioSessionError localizedDescription]);
按下home键的代码
- (void) applicationDidEnterBackground:(UIApplication *)application
{
//后台运行的尝试
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
Info.plist局部内容:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
播放乐曲调用:
NSError *_err;
AVAudioPlayer *_player;
NSString *file = [[NSString alloc ] initWithFormat:@\"/Users/hanmj/Hanmjmusic/halo.mp3\"];
_player = [ [AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:file ] error:&_err ];
[file release];
_player.volume = 1;
[_player play];
mp3文件后台播放问题,很久都找不到原因
最新推荐文章于 2021-12-21 10:46:14 发布