[更新在问题的结尾]
我曾经在我的应用程序中播放一些音频文件。
我曾经将文件存储在应用程序中,但后来我转移到On Demand Resources
和NSBundleResourceRequest
.
我IBAction
要播放一个随机文件,但自从我移到 后ODR
,它就无法正常工作了。我唯一改变的是NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
(第3行)
NSBundleResourceRequest *request1;
- (IBAction)randomPlay {
NSString *bundleRoot = [[request1 bundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"];
NSArray *onlyMP3s = [dirContents filteredArrayUsingPredicate:fltr];
.
.
.
audio = [onlyMP3s[arc4random_uniform((uint32_t)onlyMP3s.count)]
stringByReplacingOccurrencesOfString:@".mp3" withString:@""];
[self playSelectedAudio:audio];
}
dirContents
看起来像:
当它应该包含 mp3 文件时。
我在做什么错bundleRoot
?
我viewDidload
的是
- (void)viewDidLoad {
[super viewDidLoad];
tagsSet = [NSSet setWithObjects:@"sounds", nil];
request1 = [[NSBundleResourceRequest alloc] initWithTags:tagsSet];
[request1 conditionallyBeginAccessingResourcesWithCompletionHandler:^
(BOOL resourcesAvailable) {
if (resourcesAvailable) {
//don't do nothing. just use the file slater
} else {
[request1 beginAccessingResourcesWithCompletionHandler:^
(NSError * _Nullable error) {
if (error == nil) {
//download the files
} else {
}
}];
}
}];
我实际上有另一种方法来播放选定的音频(不是随机的)
-(void)playSelectedAudio:(id)audioToPlay {
NSURL *url = [NSURL fileURLWithPath:[[request1 bundle]
pathForResource:audioToPlay ofType:@"mp3"]];
它工作正常。
所以有一个问题,bundleRoot
不是我的文件所在的位置。
[更新]
我确实做到了
- (IBAction)randomPlay {
NSURL *bundleRoot = [NSURL fileURLWithPath:[[request1 bundle]
pathForResource:@"" ofType:@"mp3"]];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtURL:bundleRoot
includingPropertiesForKeys:[NSArray array]
options:0 error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:
@"self ENDSWITH '.mp3'"];
NSArray *onlyMP3s = [dirContents
filteredArrayUsingPredicate:fltr];
.
.
.
audio = [onlyMP3s[arc4random_uniform((uint32_t)onlyMP3s.count)]
stringByReplacingOccurrencesOfString:@".mp3"
withString:@""];
[self playSelectedAudio:audio];
}];
}
它几乎可以工作,但总是在播放目录中的第一个音频。