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

锁屏后继续播放其实就是利用了Audio session这个feature,具体可以看看apple的文档里面关于Audio session的部分,我是用的AVFoundation.framework这个库来播放音乐的。

全部代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 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];
}

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