1

这是我的代码:

MainViewConroller.h

#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>


@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {

    AVAudioPlayer *audioPlayer;
    NSArray *soundsArray;
}

@property(nonatomic, retain) AVAudioPlayer *audioPlayer;
@property(nonatomic, retain) NSArray *soundsArray;

-(void)prepareSounds;
- (IBAction)playSound:(UIButton *)sender;

@end

这是我的 MainViewController.m:

#import "MainViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController 

@synthesize audioPlayer;
@synthesize soundsArray;

-(void)prepareSounds
{
    NSString *filepath= [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"plist"];

    self.soundsArray = [[NSArray alloc] initWithContentsOfFile:filepath];

}

- (void)stopAudio
{
    if (audioPlayer!= nil) {
        [audioPlayer stop];
        //do some task for changing the Image i.e setting the default image
    }

}

- (IBAction)playSound:(UIButton *)sender
{
    UIButton *btn = (UIButton*)sender;

    NSString *soundName = [soundsArray objectAtIndex:(btn.tag - 1)];

    NSString *path      = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
    NSURL *file         = [[NSURL alloc] initFileURLWithPath:path];

    AVAudioPlayer *p    = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];

    self.audioPlayer    = p;

    if([audioPlayer isPlaying])
    {
        [self stopAudio];
    }

    [self.audioPlayer play];


}


- (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.
}

#pragma mark - Flipside View

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)showInfo:(id)sender
{    
    FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil];
    controller.delegate = self;
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:controller animated:YES completion:nil];
}

@end

我有 3 个按钮。在“支持文件”文件夹中,我有一个字符串数组,其中包含我要播放的声音文件的名称,名为“Sound.plist”,在“支持文件”文件夹中,我有一个名为“声音”的文件夹,其中包含声音文件。

即使我删除了 .plist 文件,我的所有按钮都播放相同的声音。它似乎总是播放“声音”文件夹中的第一个声音。有人可以提供一些见解,我觉得我已经尝试了一切。谢谢!

4

0 回答 0