2012-02-19 61 views
0

我是一位C程序員,但不是客觀的c。我試圖通過在目標c中給他這段代碼來幫助我的朋友。順便說一句,這是一個iPhone應用程序。我有所有必要的基礎,正如你所看到的,已經聲明我的聲音爲soundA,使用 - (IBAction)方法...此外,聲音是一個簡單的.wav文件,不大於100 kb。從C代碼轉換爲ObjC

- (IBAction)soundA:(id)sender { 
    CFBundleRef mainBundle = CFBundleGetMainBundle(); 
    CFURLRef soundFileURLRef; 
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, 
     (CFStringRef) @"soundA", CFSTR ("wav"), NULL); 

    UInt32 soundID; 
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); 
    AudioServicesPlaySystemSound(soundID); 
} 

任何幫助,非常感謝!非常感謝。

  • 怪人
+0

問題是什麼? – 2012-02-19 22:50:22

+1

ObjC是C的超集,所以C代碼也是ObjC代碼 – ouah 2012-02-19 22:55:37

+0

'CFBundleCopyResourceURL'在名稱中有副本,因此會返回自己的內存。在你的代碼中,'soundFileURLRef'因此泄漏。與'soundID'關聯的內存同上,因爲'AudioServicesCreateSystemSoundID'是'創建'方法。 – Tommy 2012-02-19 23:18:33

回答

1

也許嘗試從一個unsigned int將其更改爲SystemSoundID

- (IBAction)soundA:(id)sender { 
     CFBundleRef mainBundle = CFBundleGetMainBundle(); 
     CFURLRef soundFileURLRef; 
     soundFileURLRef = CFBundleCopyResourceURL(mainBundle, 
      (CFStringRef) @"soundA", CFSTR ("wav"), NULL); 

     SystemSoundID soundID; 
     AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); 
     AudioServicesPlaySystemSound(soundID); 
    } 

或者去一個更Objective-C的方法:

- (IBAction)soundA:(id)sender { 
     NSString *path = [NSString stringWithFormat: @"%@/%@", 
        [[NSBundle mainBundle] resourcePath], name]; 


     NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO]; 
     SystemSoundID soundID; 
     AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID); 
     AudioServicesPlaySystemSound(soundID); 
    } 
+0

或甚至'[[NSBundle mainBundle] URLForResource:@「soundA」withExtension:@「wav」]'將前兩行摺疊下來? – Tommy 2012-02-19 23:16:27

+0

好的,但如果你使用[[NSBundle mainBundle] URLForResource:@「soundA」withExtension:@「wav」] ... *路徑將不會被聲明。我怎麼能解決這個問題? – leesuh 2012-02-19 23:23:36

+0

逐字使用第二種方法來避開它。 – CodaFi 2012-02-19 23:25:52