iOS应用程序崩溃 - [NSURL initFileURLWithPath:]

Mat*_*van 1 macos compiler-errors objective-c ios

我是一个业余的ios开发人员,版本4.6的xcode和OSX 10.8.4.我正在尝试制作一个播放声音的应用程序但是当我尝试运行该应用程序时,我收到此消息:

*由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* - [NSURL initFileURLWithPath:]:nil string parameter'

我的应用程序也不会启动.

这是我的视图controller.h的代码:

      ViewController.h:

 #import <UIKit/UIKit.h>
#import <RevMobAds/RevMobAds.h>
#import <AVFoundation/AVFoundation.h>


@interface ViewController : UIViewController 



- (IBAction)playButton:(id)sender;
- (IBAction)stopButton:(id)sender;

@end
Run Code Online (Sandbox Code Playgroud)

这是我的视图controller.m:

      Viewcontroller.m:


#import "ViewController.h"
#import <RevMobAds/RevMobAds.h>


@interface ViewController ()
{
AVAudioPlayer *avPlayer;
}
@end

@implementation ViewController 
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *stringPath = [[NSBundle mainBundle]pathForResource:@"98648__dobroide__20100606-mosquito" ofType:@"mp3"];

NSURL *url = [NSURL fileURLWithPath:stringPath];

NSError *error;

avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];

[avPlayer setNumberOfLoops:-1];


}

- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.

 }


- (IBAction)playButton:(id)sender {
[avPlayer play];
}

- (IBAction)stopButton:(id)sender {
[avPlayer pause];

}
@end
Run Code Online (Sandbox Code Playgroud)

Joe*_*oel 6

问题pathForResource是返回零.您是否已将确切的文件名添加到捆绑包中?

此外,您应该在继续加载播放器之前stringPatherror之前进行测试.例如:

NSString *stringPath = [[NSBundle mainBundle]pathForResource:@"98648__dobroide__20100606-mosquito" ofType:@"mp3"];
if (stringPath) {
    NSURL *url = [NSURL fileURLWithPath:stringPath];
    NSError *error;
    avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
    if (!error) {
        [avPlayer setNumberOfLoops:-1];
    } else {
        NSLog(@"Error occurred: %@", [error localizedDescription]);
    }
} else {
    NSLog(@"Resource not found");
}
Run Code Online (Sandbox Code Playgroud)