解决关于如何实现锁屏后的继续播放

解决关于如何实现锁屏后继续播放音乐的问题



锁屏后继续播放其实就是利用了Audio session这个feature,具体可以看看apple的文档里面关于Audiosession的部分,我是用的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];


}

你可能感兴趣的:(解决关于如何实现锁屏后的继续播放)