2017-10-18 20 views
1

我是斯威夫特傢伙回去做一些Objc工作,我想一個聲音添加到我的應用程序,問題在於,pathnull試圖找到時文件定位音頻文件的目標C發揮

該文件位於myProj/Resources/Sounds/genericButtonPress.wav

NSString *path = [[NSBundle mainBundle] pathForResource:@"myProj/Resources/Sounds/genericButtonPress" ofType:@"wav"]; 
    NSLog(@"%@", path); // NULL 
    NSURL *url = [NSURL fileURLWithPath:path]; 

    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL]; 
    [player play]; 

從文檔,它看起來像pathForResource必須是絕對的,但我也試圖與剛剛genericButtonPress爲我的字符串。

想在這裏得到一些幫助。謝謝!

+0

您是否試過'NSString * path = [[NSBundle mainBundle] pathForResource:@「genericButtonPress」ofType:@「wav」];'? –

+0

我做到了。沒有運氣。 –

+0

對於你的問題,你說'wav'文件名是'mysound'。但是在你的代碼中你正在尋找'genericButtonPress'。你確定你沒有使用錯誤的名字嗎?嘗試'NSString * path = [[NSBundle mainBundle] pathForResource:@「myProj/Resources/Sounds/mysound」ofType:@「wav」];'。 –

回答

0

答案是這樣的:

記住孩子,始終確保您的文件分配給你的適當的目標或東西不會出現,並將無法正常工作。這尤其適用於字體和音頻文件。

+0

我給你確切的答案兄弟。 – user3182143

+0

如果你嘗試我的代碼,它完美的作品。 – user3182143

0

我的解決辦法是

ViewController.h

#import <UIKit/UIKit.h> 
#import <AVKit/AVKit.h> 

@interface ViewController : UIViewController 
@property (nonatomic,strong)AVAudioPlayer *player; 
- (IBAction)actionPlayAudio:(id)sender; 
@end 

ViewController.m

#import "ViewController.h" 

@interface ViewController() 
@end 
@implementation ViewController 
@synthesize player; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
} 
- (IBAction)actionPlayAudio:(id)sender { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"youraudiofilename" ofType:@"wav"]; 
    NSURL *soundFileURL = [NSURL fileURLWithPath:path]; 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
    [player play]; 
}