开发者

code to play sound programmatically using a button on the iphone

I am trying to figure out how to hook up a but开发者_StackOverflow中文版ton to play a sound programmatically without using 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 inherits its target/action methods from UIControl.


To hook up the button, make your playSound method the handler for the button's UIControlEventTouchUpInside event. Assuming this is in a view controller, you might want to put this in the viewDidLoad method:

[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.

You should create a new AVAudioPlayer member for the class to avoid this.

@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.

(I did this without declaring myAudio as a @property, but that's not strictly necessary)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜