1

我是 Objective C 的新手,我正在开发一个在 uibutton 的触摸事件上播放声音的应用程序。当我触摸按钮时,它改变的是图像和音频开始播放。音频播放完毕后,我想放置 uibutton 的原始图像。我怎样才能做到这一点?我怎样才能捕捉到音频结束的事件?我正在使用该代码:

- (SystemSoundID) createSoundID: (NSString*)name
{
    NSString *path = [NSString stringWithFormat: @"%@/%@",
    [[NSBundle mainBundle] resourcePath], name];              
    NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
    return soundID;
} 

viewDidLoad

我打电话

freq = [self createSoundID: @"freq.wav"];

在按钮触摸时调用的函数中,我使用:

AudioServicesPlaySystemSound(freq);

我能怎么做?谢谢!

4

2 回答 2

2

不确定是否可以使用 AudioService API,但您可以AVAudioPlayer改用并分配一个实现AVAudioPlayerDelegate协议并在audioPlayerDidFinishPlaying:successfully:调用时执行某些操作的委托。

记得添加AVFoundation框架。

例子:

在您的接口定义中:

#import <AVFoundation/AVFoundation.h>

...

@inteface SomeViewController : UIViewController <AVAudioPlayerDelegate>

...

@propety(nonatomic, retain) AVAudioPlayer *player;

在您的实施中:

@synthesize player;

...

// in some viewDidLoad or init method
self.player = [[[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:NULL] autorelease];
self.player.delegate = self;

...

- (void)pressButton:(id)sender {
  // set play image
  [self.player stop];
  self.player.currentTime = 0;
  [self.player play];
}

...

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
   // set finish image
}

...

# in some dealloc or viewDidUnload method
self.player = nil;
于 2011-09-28T11:23:04.630 回答
0

您想使用 AudioService API 是可能的AudioServicesAddSystemSoundCompletion

于 2019-07-02T09:52:34.840 回答