使用AVAudioPlayer我试图在iphone播放器播放时播放声音。此外当设备被锁定。 事情是,在iPhone 4s ios 7 - 工作正常。 但是,iPhone 6与6和7 ios没有任何反应。AVAudioPlayer在锁定时不会在iPhone 5中播放音频
在-Info.plist
在Required background modes
我Player.h
写
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"]];
}
问候。
您确认您已加入该行的'info.plist'为合适的项目目标,而不是'test'目标?我犯了这个错误,花了大约2.5天的时间才弄明白!我认为一切都是正确的,它不工作! – Neeku
@Neeku,谢谢你的回复!是的,我将该行添加到项目目标,而不是测试目标。 –