简体   繁体   English

当 iPhone 像 iPod App 一样被锁定时继续播放音频

[英]Continue audio playback when iPhone is locked like iPod App

I need to continue the playback even when the user locks the phone.即使用户锁定手机,我也需要继续播放。 I've seen some solution over the internet, but none of them seem to work, such as:我在互联网上看到了一些解决方案,但它们似乎都不起作用,例如:

AudioSessionSetActive(true);
    // Set up audio session, to prevent iPhone from deep sleeping, while playing sounds
    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty (
                             kAudioSessionProperty_AudioCategory,
                             sizeof (sessionCategory),
                             &sessionCategory
                             );

I'm inlcuding AVFoundation , AudioToolbox , and MediaPlayer .我包括AVFoundationAudioToolboxMediaPlayer

I figured out how to do this.我想出了如何做到这一点。

First of all, include these frameworks to your project: AudioToolbox , CoreAudio , MediaPlayer and AVFoundation .首先,将这些框架包含到您的项目中: AudioToolboxCoreAudioMediaPlayerAVFoundation 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!享受你的背景音频播放应用程序!

Refer following Links:参考以下链接:

How to Continue Music Play after Screen Auto-Lock 屏幕自动锁定后如何继续播放音乐

Playing audio while iPhone is locked 在 iPhone 锁定时播放音频

how to play music using AVAudioPlayer when screen os locked 屏幕锁定时如何使用 AVAudioPlayer 播放音乐

Try :尝试

// Set up audio session, to prevent iPhone from deep sleeping, while playing sounds
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;

AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory);

AudioSessionSetActive(true);

If you have a playlist for example and want to play the next song while in background mode or lock mode add this line of code on your viewDidLoad:例如,如果您有一个播放列表,并且想在后台模式或锁定模式下播放下一首歌曲,请在您的 viewDidLoad 中添加以下代码行:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

This makes the app supports remote control events.这使得应用程序支持远程控制事件。

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

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