如何获得在iPhone上的资源的文件系统路径?
-
19-09-2019 - |
题
在iPhone上我需要得到该资源的路径。 OK,这样做,但是当涉及到CFURLCreateFromFileSystemRepresentation的事情,我只是不知道如何解决这个问题。为什么会出现这个错误?任何溶液或解决方法将高度赞赏。谢谢你在前进。
我才能在iPhone上使用AudioQueue播放音频采取一起来看看下面的例子: SpeakHere,AudioQueueTools(从SimpleSDK目录)和AudioQueueTest。我试着做这做那,试图把拼图在一起。现在,我被困在此。程序崩溃,因为来自sndFile抛出上述异常的。
我使用AVAudioPlayer发挥每一个声音在我的iPhone游戏。在真正的iPhone设备,它竟然是在声音被打得非常laggy,所以我决定我需要使用AudioQueue。
- (id) initWithFile: (NSString*) argv{
if (self = [super init]){
NSString *soundFilePath = [[NSBundle mainBundle]
pathForResource:argv
ofType:@"mp3"];
int len = [soundFilePath length];
char* fpath = new char[len];
//this is for changing NSString into char* to match
//CFURLCreateFromFileSystemRepresentation function's requirement.
for (int i = 0; i < [soundFilePath length]; i++){
fpath[i] = [soundFilePath characterAtIndex:i];
}
CFURLRef sndFile = CFURLCreateFromFileSystemRepresentation
(NULL, (const UInt8 *)fpath, strlen(fpath), false);
if (!sndFile) {
NSLog(@"sndFile error");
XThrowIfError (!sndFile, "can't parse file path");
}
}
解决方案
为什么你需要一个CFURL?
如果您有其他地方的方法,需要一个CFURL,你可以简单地使用NSURL多亏了免费桥接。因此,要创建NSURL,你只是做:
NSString * soundFilePath = [[NSBundle mainBundle]
pathForResource:argv
ofType:@"mp3"];
NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath];
在一般情况下,如果你发现自己使用CF对象你可能做错了什么。
其他提示
我不知道这是否会干掉你的异常的,但有一个简单的NSString
转换为char
阵列方式。下面是如何将我写此方法:
- (id) initWithFile:(NSString*) argv
{
if ((self = [super init]) == nil) { return nil; }
NSString * soundFilePath = [[NSBundle mainBundle]
pathForResource:argv
ofType:@"mp3"];
CFURLRef sndFile = CFURLCreateFromFileSystemRepresentation
(NULL, [soundFilePath UTF8String],
[soundFilePath length], NO);
if (!sndFile) { NSLog(@"sndFile error"); }
XThrowIfError (!sndFile, "can't parse file path");
...
}
或者,由于CFURL
是“免费桥接”与NSURL
,你可以简单地做:
- (id) initWithFile:(NSString*) argv
{
if ((self = [super init]) == nil) { return nil; }
NSString * soundFilePath = [[NSBundle mainBundle]
pathForResource:argv
ofType:@"mp3"];
NSURL * sndFile = [NSURL URLWithString:[soundFilePath
stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding]];
if (!sndFile) { NSLog(@"sndFile error"); }
XThrowIfError (!sndFile, "can't parse file path");
...
}
不隶属于 StackOverflow