简体   繁体   English

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

[英]code to play sound programmatically using a button on the iphone

I am trying to figure out how to hook up a button to play a sound programmatically without using IB. 我试图弄清楚如何在不使用IB的情况下连接按钮以编程方式播放声音。 I have the code to play the sound, but have no way of hooking the button up to play the sound? 我有播放声音的代码,但是没有办法挂上按钮来播放声音? any help? 有什么帮助吗?

here is my code that I'm using: 这是我正在使用的代码:

     - (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];
    }
[button addTarget:self action:@selector(playSound) forControlEvents:UIControlEventTouchUpInside];

UIButton从UIControl继承其target / action方法。

To hook up the button, make your playSound method the handler for the button's UIControlEventTouchUpInside event. 要连接按钮,请使playSound方法成为按钮的UIControlEventTouchUpInside事件的处理程序。 Assuming this is in a view controller, you might want to put this in the viewDidLoad method: 假设这是在视图控制器中,则可能需要将其放在viewDidLoad方法中:

[button addTarget:self action:@selector(playSound) forControlEvents:UIControlEventTouchUpInside]; 

FYI, you're leaking memory because you're alloc -ing an object but never release -ing it. 仅供参考,您正在泄漏内存,因为您正在alloc对象,但从不release对象。

You should create a new AVAudioPlayer member for the class to avoid this. 您应该为该类创建一个新的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];
}

Don't forget to put [myAudio release] in your dealloc method. 不要忘记将[myAudio release]放入您的dealloc方法中。

(I did this without declaring myAudio as a @property , but that's not strictly necessary) (我这样做是不宣myAudio@property ,但是这不是绝对必要)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM