在iOS中条件变为真时播放声音

在iOS中条件变为真时播放声音,ios,uiviewcontroller,Ios,Uiviewcontroller,我想做一个有文字的标签,当标签变成我想要的文字时, 我想要一个声音只播放一次 我的意思是,我有一个按钮,当点击它检查标签文本,如果标签文本是我想要的,它播放声音的时间不超过2秒 这是界面部分viewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController { UILabel *label; } @property (nonatomic , strong) IBOut

我想做一个有文字的标签,当标签变成我想要的文字时, 我想要一个声音只播放一次

我的意思是,我有一个按钮,当点击它检查标签文本,如果标签文本是我想要的,它播放声音的时间不超过2秒

这是界面部分viewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    UILabel *label;

}

@property (nonatomic , strong) IBOutlet UILabel *label;

-(IBAction) checkLabelText:(UIButton *)sender;

@end


this the implementation section (viewController.m)

#import "viewController.h"

@implementation ViewController

@synthesize label

-(IBAction) checkLabelText:(UIButton *)sender
{
    if([label.text isEqualToString:@"hi world"])
    {
        //i want the code of playing the sound here
    }

}

@end

首先,if语句应该是这样的:

if([label.text isEqualToString:@"hi world"])
{

}
接下来,如果要播放音频,请执行以下操作:

if([label.text isEqualToString:@"hi world"])
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"yourSound" ofType:@"mp3"];
    self.audio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    [self.audio play];
}
在@interface中:

如果您有任何问题,请不要犹豫


-Abdullah Shafique

你想要代码吗?请提供更多细节。我想要框架或我可以使用的类。好的,我刚刚发布了一个答案。如果你有任何问题,请询问Hanks,谢谢你回答我,谢谢你告诉我If blocks中代码中的错误,我修复了它,这是我在stackOverFlow中的第一个问题
@interface ViewController : UIViewController
@property(nonatomic) AVAudioPlayer *audio;
@end