###前提・実現したいこと
質問をご覧いただきまして、ありがとうございます。
元々swiftから勉強を始め、最近Objective-Cを勉強し始めました。
「ボタンがタップされた時に音が鳴る」
というシンプルな機能を実現したいのですが、コードにエラーはなく、
シミュレータでボタンをタップした時に
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
というエラーが出てしまいます。
NSURL initFileURLWithPathで設定したurlにnilが格納されてしまっていることが原因と思い、以下を参照しながら色々と試行錯誤しているのですが、なかなか上手くいきません。
参照①-Stack Overflow
参照②-Stack Overflow
以下にソースコードを付します。
###ソースコード
ViewController.m
#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController()<AVAudioPlayerDelegate> - (IBAction)wineTapped:(UIButton *)sender; @property(nonatomic) AVAudioPlayer *audioplayer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)wineTapped:(UIButton *)sender{ long tagNum = sender.tag; printf("%ld", sender.tag); NSError *error = nil; if(tagNum == 1){ NSLog(@"%ld", tagNum); NSString *path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]; NSURL *url1 = [[NSURL alloc] initFileURLWithPath:path1]; self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:&error]; [self.audioplayer prepareToPlay]; [self.audioplayer play]; } else if(tagNum == 2){ NSLog(@"%ld", tagNum); NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"]; NSURL *url2 = [[NSURL alloc] initFileURLWithPath:path2]; self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url2 error:&error]; [self.audioplayer prepareToPlay]; [self.audioplayer play]; } else if(tagNum == 3){ NSLog(@"%ld", tagNum); NSString *path3 = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"mp3"]; NSURL *url3 = [[NSURL alloc] initFileURLWithPath:path3]; self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url3 error:&error]; [self.audioplayer prepareToPlay]; [self.audioplayer play]; } else if(tagNum == 4){ NSLog(@"%ld", tagNum); NSString *path4 = [[NSBundle mainBundle] pathForResource:@"4" ofType:@"mp3"]; NSURL *url4 = [[NSURL alloc] initFileURLWithPath:path4]; self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url4 error:&error]; [self.audioplayer prepareToPlay]; [self.audioplayer play]; } else if(tagNum == 5){ NSLog(@"%ld", tagNum); NSString *path5 = [[NSBundle mainBundle] pathForResource:@"5" ofType:@"mp3"]; NSURL *url5 = [[NSURL alloc] initFileURLWithPath:path5]; self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url5 error:&error]; [self.audioplayer prepareToPlay]; [self.audioplayer play]; } } @end
お詳しい方いらっしゃいましたら、改善方法をご教示いただけると幸いです。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/12/03 12:23