ios - Termination because of NSEexception? -
this in .m file, xcode. main goal have button play sound(not @ same time) when has 2 sound files attached , randomizer doesn't play same sound twice or wouldn't twice. run code , when click on yes button lldb nsesception error occurs. ive looked around lldb exception error solution found go view-controller delete yellow exclamation mark;which didn't not solve issue..
#import "viewcontroller.h" #import <avfoundation/avaudioplayer.h> @interface viewcontroller () @end @implementation viewcontroller : uiviewcontroller - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of resources can recreated. } - (ibaction)yes{ nsmutablearray *array=[nsmutablearray arraywithobjects: @"yes.mp3", @"yes 3.mp3", nil]; int i=0; for(i=0;i<=[array count]; i++) { nsinteger rand=(arc4random() %1); [array exchangeobjectatindex:i withobjectatindex:rand]; } nsstring *sound = [array objectatindex:i]; avaudioplayer* audioplayer=[[avaudioplayer alloc] initwithcontentsofurl:[nsurl fileurlwithpath: [[nsbundle mainbundle]pathforresource:sound oftype:@"mp3"]] error:null]; [audioplayer play]; } @end
you have 4 issues. loop range, calculation of random value, , array index usage after loop, , specify sound file's extension twice.
the loop , random value should be:
for(nsuinteger = 0; < [array count]; i++) { nsinteger rand = arc4random_uniform(array.count); [array exchangeobjectatindex:i withobjectatindex:rand]; }
- notice
<=
<
. - your calculation of random number returned 0.
it's unclear want sound
value after loop. written, try access using i
large. need specify value in range 0
array.count - 1
.
if want 1st (now random) value array, use:
nsstring *sound = [array firstobject];
update:
after realizing want play 1 of 2 sounds randomly, think code can simplified to:
- (ibaction)yes { nsinteger rand = arc4random_uniform(2); nsstring sound = rand == 0 ? @"yes" : @"yes 3"; nsurl *url = [[nsbundle mainbundle] urlforresource:sound withextension:@"mp3"]; avaudioplayer* audioplayer = [[avaudioplayer alloc] initwithcontentsofurl:url error:nil]; [audioplayer play]; }
Comments
Post a Comment