2011-09-09 66 views
0

我正在通過const char *值進入函數,用這個函數打開指定的音頻文件AudioFileOpenURL方法。所以我需要一個CFURLRef值。但我使用相對路徑,像 聲音/ click.wav 但在這種情況下AudioFileOpenURL無法打開文件(文件未找到錯誤)。所以我需要擴展相對路徑並將完整路徑傳遞給此方法。我發現最好的解決方案是: 獲取包的url,獲取資源文件夾的url,從CFString構造CFURL,這是從字節.....構建非常惱人。如何使用CoreFoundation輕鬆獲取mac os x中的資源位置?

CFBundleRef bundle = CFBundleGetMainBundle(); 

CFURLRef bundleUrl = CFBundleCopyBundleURL(bundle); 
CFURLRef resUrl = CFBundleCopyResourcesDirectoryURL(bundle); 
CFStringRef cfsName = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), kCFStringEncodingASCII, 1); 

CFMutableStringRef fileName = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFURLGetString(bundleUrl)); 
CFStringAppend(fileName, CFURLGetString(resUrl)); 
CFStringAppend(fileName, cfsName); 

CFURLRef theURL = CFURLCreateWithString(kCFAllocatorDefault, fileName, 0); 

CFRelease(fileName); 
CFRelease(cfsName); 
CFRelease(resUrl); 
CFRelease(bundleUrl); 

有沒有更簡單的方法呢?因爲在iPhone上的下一個代碼:

CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false); 

工作就像一個魅力。

回答

1

大部分CF字符串創建繁忙是因爲你從C字符串開始。取而代之的是從literal CFString或NSString開始,你會更快樂。

將子路徑作爲CF/NSString傳遞給函數後,使用CFURLCreateCopyAppendingPathComponent將該子路徑追加到該資源包的資源目錄URL。生成的URL是聲音文件的URL。