-(void)setAudioPlayer{
//加入播放按钮
if (playButton==nil) {
playButton = [UIButton buttonWithType:UIButtonTypeCustom];
playButton.frame = CGRectMake(110, 120, 80, 80);
[playButton setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
playButton.alpha = 0.5;
[firstPage addSubview:playButton];
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
if (soundPath!=nil) {
float volumn = [bookSetting getUpdatedVolumn];
player = [[SoundPlayer alloc]initWithPath:soundPath bookName:bookName volumn:volumn];
}
[pool release];
}
-(void)setPlayInBackground{
if (soundPath!=nil) {
//后台播放
[self registerForBackgroundNotifications];
OSStatus result = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (result)
NSLog(@"Error initializing audio session! %d", result);
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError)
NSLog(@"Error setting category! %d", setCategoryError);
result = AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, RouteChangeListener, self);
if (result)
NSLog(@"Could not add property listener! %d", result);
}
}
#pragma mark AudioSession handlers
void RouteChangeListener(void * inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void * inData){
BookContentView2* This = (BookContentView2*)inClientData;
if (inID == kAudioSessionProperty_AudioRouteChange) {
CFDictionaryRef routeDict = (CFDictionaryRef)inData;
NSNumber* reasonValue = (NSNumber*)CFDictionaryGetValue(routeDict, CFSTR(kAudioSession_AudioRouteChangeKey_Reason));
int reason = [reasonValue intValue];
if (reason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
[This.player stop];
}
}
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)p
{
NSLog(@"Interruption begin. Updating UI for new state");
// the object has already been paused, we just need to update UI
if (inBackground)
{
[self updateViewForPlayerStateInBackground:p];
}
else
{
[self updateViewForPlayerState:p];
}
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)p
{
NSLog(@"Interruption ended. Resuming playback");
[self startPlaybackForPlayer:p];
}
#pragma mark background notifications
- (void)registerForBackgroundNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(setInBackgroundFlag)
name:UIApplicationWillResignActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearInBackgroundFlag)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
- (void)setInBackgroundFlag
{
inBackground = YES;
}
- (void)clearInBackgroundFlag
{
inBackground = NO;
}