playing Random sounds on a soundboard app

2019-03-04 19:56发布

问题:

I have been trying to create a app that when I press a button it plays a sound but then when I press the same button again it plays a different sound I don't mind if it plays it totally random all the time or if it plays a different sound a time but the same order every time hope this make sense guys

Here's all the code I have:

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController



@class AVAudioPlayer;


@interface ViewController : UIViewController

-(IBAction)PlayRandomSound;
@property (nonatomic, retain) AVAudioPlayer *soundPlayer;




@end

.m

#import "ViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
@interface ViewController ()

@end

@implementation ViewController


@synthesize soundPlayer = _soundPlayer;


-(IBAction)PlayRandomSound{

    int randomNumber = arc4random() % 8 + 1;

    NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"mp3"]];


    _soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];

    [_soundPlayer prepareToPlay];
    [_soundPlayer play];


    NSLog(@"randomNumber is %d", randomNumber);
    NSLog(@"tmpFilename is %@", soundURL);
}

Here the errors I have in images

I have also inserted the AVFoundation.Framework and AudioToolbox.Frame

回答1:

You have many problems with this. It's hard to answer your actual question because you have lots of little problems that are getting in the way.

To give you some help:

this is incorrect:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@class AVAudioPlayer;

@interface ViewController : UIViewController

As the image you have posted, even Xcode is trying to help you. The @class forward declaration is in the wrong place. Try putting it just after the #import statements. Because of this your soundplayer isn't being created properly and you are getting other warnings.

You need to fix all the errors and then all the warnings and keep doing this until it builds cleanly.