转自:http://www.cocoachina.com/bbs/read.php?tid-26984.html
今天收到论坛一兄弟的PM,询问实现黑屏后继续播放的问题,考虑可能有很多人有这个需求,所以单独开个帖子说明一下。
另外我在做这个电子书的过程中也积累了一些经验,主要是Unviersal App相关的,如何在一个app里支持所有的iPhone/iTouch,iPad,iPhone 4等,以及支持所有系统版本,从3.0到3.1.3,3.2,3.2.1,4.0到4.0.1,改天整理一下和大家分享
引用
hi~ ga兄说你做过一个
音乐程序。锁屏后可以继续播放
有没有方法可以在
iphone黑屏休眠时候让程序继续执行的方法呢
[UIApplication sharedApplication].idleTimerDisabled = YES;太费电了,不锁屏
音乐好像本来就可以背景播放。。。
不知道你又没有什么方法
感谢
锁屏后继续播放其实就是利用了Audio session这个feature,具体可以看看
apple的文档里面关于Audio session的部分,我是用的AVFoundation.framework这个库来播放音乐的。
全部
代码如下:
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 0;
//The C Style function call
AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
//alloc a new player
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: @"your audio file path" error:nil];
//prepare and set delegate
[newPlayer prepareToPlay];
[newPlayer setDelegate:self];
//play audio
[newPlayer play];
//pause or stop audio
[newPlayer pause];
[newPlayer stop];
//restart audio playing
if (newPlayer.playing)
{
[newPlayer pause];
newPlayer.currentTime = 0;
[newPlayer play];
}
|
[ 此帖被ttgb在2010-07-22 18:06重新编辑 ]