使用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,謝謝你的回覆!是的,我將該行添加到項目目標,而不是測試目標。 –