本文介绍了锁定后,AVAudioPlayer无法在iPhone 5中播放音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用AVAudioPlayer我正在尝试在iphone播放器播放声音.同样在设备锁定时.事实是,在iPhone 4s ios 7中-可以正常工作.但是在装有6和7 ios的iPhone 5上,什么也没发生.
Using AVAudioPlayer I'm trying to play sounds while the iphone player is playing. Also when device is locked.The thing is, that in iPhone 4s ios 7 - works fine.But on iPhone 5 with 6 and 7 ios nothing happens.
在Required background modes
的-Info.plist
中,我写了
App plays audio or streams audio/video using AirPlay
:
@property (nonatomic, strong) AVAudioPlayer *notificationPlayer;
<AVAudioPlayerDelegate, AVAudioSessionDelegate>
与包含#import <AVFoundation/AVFoundation.h>
也在Player.m
//this is called on viewDidLoad
-(void) prepareSound{
[[AVAudioSession sharedInstance] setDelegate:self];
}
//overriden function
- (void)playAudio:(NSString *)path{
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryAmbient
withOptions: AVAudioSessionCategoryOptionDuckOthers
error: nil];
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:path];
self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
self.notificationPlayer.delegate = self;
[self.notificationPlayer prepareToPlay];
[self.notificationPlayer setVolume:1.0];
[self.notificationPlayer play];
if (error) {
NSLog(@"error %@",[error localizedDescription]);
}
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player stop];
[[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient
withOptions: 0
error: nil];
[[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil];
}
//Call from here
-(void) customMethod{
[self playAudio:[[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"]];
}
致谢.
推荐答案
我应该使用以下代码
- (void)playAudio:(NSString *)path {
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:path];
self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
self.notificationPlayer.delegate = self;
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
NSError *errorSession = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];
[audioSession setActive:NO error:&errorSession];
[self.notificationPlayer prepareToPlay];
[self.notificationPlayer setVolume:1.0];
[self.notificationPlayer play];
if (error) {
NSLog(@"error %@",[error localizedDescription]);
}
NSLog(@"Should play music");
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player stop];
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}
这篇关于锁定后,AVAudioPlayer无法在iPhone 5中播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!