使用iphone上的按钮以编程方式播放声音的代码

使用iphone上的按钮以编程方式播放声音的代码,iphone,objective-c,audio,Iphone,Objective C,Audio,我正试图弄清楚如何在不使用IB的情况下通过编程连接一个按钮来播放声音。我有播放声音的代码,但没有办法连接按钮来播放声音?有什么帮助吗 以下是我正在使用的代码: - (void)playSound { NSString *path = [[NSBundle mainBundle] pathForResource:@"boing_1" ofType:@"wav"]; AVAudioPlayer* myAudio = [[AVAudioPlayer a

我正试图弄清楚如何在不使用IB的情况下通过编程连接一个按钮来播放声音。我有播放声音的代码,但没有办法连接按钮来播放声音?有什么帮助吗

以下是我正在使用的代码:

     - (void)playSound
    {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"boing_1" ofType:@"wav"];
        AVAudioPlayer* myAudio = [[AVAudioPlayer alloc] 
                 initWithContentsOfURL:[NSURL fileURLWithPath:path error:NULL]];
        myAudio.delegate = self;
        myAudio.volume = 2.0;
        myAudio.numberOfLoops = 1;
        [myAudio play];
    }

UIButton从继承其目标/操作方法。

要连接按钮,请将您的
playSound
方法作为按钮的
UIControlEventTouchUpInside
事件的处理程序。假设这是在视图控制器中,您可能希望将其放在
viewDidLoad
方法中:

[button addTarget:self action:@selector(playSound) forControlEvents:UIControlEventTouchUpInside]; 
仅供参考,您正在泄漏内存,因为您正在
分配对象,但从未
释放它

您应该为该类创建一个新的
AVAudioPlayer
成员以避免这种情况

@interface MyViewController : ...
{
    ...
    AVAudioPlayer* myAudio;
    ...
}

- (void)playSound
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"boing_1" ofType:@"wav"];
    [myAudio release];
    myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path error:NULL]];
    myAudio.delegate = self;
    myAudio.volume = 2.0;
    myAudio.numberOfLoops = 1;
    [myAudio play];
}
不要忘记将
[myAudio release]
放入您的
dealoc
方法中


(我这样做时没有将
myAudio
声明为
@属性
,但这不是严格必要的)

他可能不应该每次调用该方法时都分配一个新的AVAudioPlayer实例。执行类似以下操作:
if(!myAudio){myAudio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path error:NULL]];}
Valid comment,尽管我认为首先应该是“让它工作起来”。)这就是我一直在寻找的…我相信我以前见过类似的东西,但不记得在哪里…这应该很有效!
@interface MyViewController : ...
{
    ...
    AVAudioPlayer* myAudio;
    ...
}

- (void)playSound
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"boing_1" ofType:@"wav"];
    [myAudio release];
    myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path error:NULL]];
    myAudio.delegate = self;
    myAudio.volume = 2.0;
    myAudio.numberOfLoops = 1;
    [myAudio play];
}