2017-10-18 58 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]; 
}