使用 AVAudioPlayer 我尝试在 iphone 播放器播放时播放声音。当设备锁定时也是如此。
问题是,在 iPhone 4s ios 7 中,效果很好。
但在带有 6 和 7 ios 的 iPhone 5 上没有任何反应。
In the -Info.plist
in Required background modes
我写
App plays audio or streams audio/video using AirPlay
in Player.h
实施的:
@property (nonatomic, strong) AVAudioPlayer *notificationPlayer;
<AVAudioPlayerDelegate, AVAudioSessionDelegate>
with
#import <AVFoundation/AVFoundation.h>
包括
Also in 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"]];
}
Regards.
在后台播放声音时要注意的另一个非常重要的事情是您是否拥有该文件的权限。如果您正在播放捆绑文件,则您拥有权限,并且可能有一些从互联网流式传输的文件,但如果您已将媒体下载到文档目录中,则必须适当设置权限,特别是当您的应用程序本机锁定文件时。
这往往与许多人所看到的症状相符,即文件将继续播放几秒钟(5 到 15 秒),然后停止。如果您正在监听已完成的方法,您将看到一个错误标志。原因:当您第一次播放音频文件时,AVAudioPlayer 不会将整个音频文件加载到内存中。
例子:
NSURL url = [NSURL URLWithString:@""];
NSError *error = nil;
[[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey :
NSFileProtectionCompleteUntilFirstUserAuthentication} ofItemAtPath:[url path] error:&error];
您的选择如下:
NSFileProtectionComplete;
NSFileProtectionCompleteUnlessOpen;
NSFileProtectionCompleteUntilFirstUserAuthentication;
NSFileProtectionNone;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)