简体   繁体   English

当iPhone /设备进入睡眠或锁定状态时继续播放音频

[英]continue playing audio when iphone/device goes sleep or locked

I am using the following code to keep playing audio when iPhone/iPod goes sleep or locked. 我正在使用以下代码在iPhone / iPod进入睡眠或锁定状态时继续播放音频。

mv = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:@"http://myurl/myMusic.mp3"]];
mv.movieSourceType = MPMovieSourceTypeUnknown;
[self.view addSubview:mv.view];
[mv play];

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory); AudioSessionSetActive(true);  

By using this code my device is not going into sleep mode but what i want is, device should go in sleep mode but audio should not stop playing. 通过使用此代码,我的设备不会进入睡眠模式,但我想要的是,设备应进入睡眠模式,但音频不应停止播放。
I have added Required background modes and App plays audio in my info.plist file. 我已经添加了Required background modes并且App plays audio在我的info.plist文件中App plays audio

Please suggest me where am I wrong? 请建议我我在哪里错了? Why the device is not going into sleep mode/locked? 为什么设备没有进入睡眠模式/锁定?

Use this code in viewdidload: 在viewdidload中使用以下代码:

NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

It is working fine for me. 对我来说很好。

First of all, include these frameworks to your project: AudioToolbox, CoreAudio, MediaPlayer and AVFoundation. 首先,在您的项目中包括以下框架:AudioToolbox,CoreAudio,MediaPlayer和AVFoundation。 Import them all to the viewController where your player will be placed. 将它们全部导入到放置播放器的viewController中。 After you allocated and started playing the audio, insert the following code: 分配并开始播放音频后,请插入以下代码:

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory);
AudioSessionSetActive(true);

And finally, go to your app Info.plist file and add a row named UIBackgroundModes. 最后,转到您的应用程序Info.plist文件,并添加名为UIBackgroundModes的行。 The new row will be an array and will contain 1 item, the item 0. To this you just set the value as audio. 新行将是一个数组,并将包含1个项目,即0项目。为此,您只需将值设置为audio。 And you're done! 大功告成! Enjoy you're background audio playing app! 享受您的背景音频播放应用程序吧!

hope it helps. 希望能帮助到你。 happy coding :) 快乐的编码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM