我当前的按钮代码是。
-(IBAction)playsnare;
{
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundfileURLRef;
soundfileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"snare", CFSTR ("wav"), NULL);
UInt32 SoundID;
AudioServicesCreateSystemSoundID(soundfileURLRef, &SoundID);
AudioServicesPlaySystemSound(SoundID);
}
我可以添加什么来使按钮在按下时播放,在没有按下时停止按钮。
答案 0 :(得分:4)
您播放音频样本的实现不允许这样做。由于您使用 AudioToolbox 框架中的 AudioServicesPlaySystemSound ,因此触发音频样本后无法停止播放。只有在完成播放后才能收到回叫。
这种播放声音的方式也有其他限制(取自文档)
此外,当您使用AudioServicesPlaySystemSound函数时:
播放当前系统音量,没有编程 音量控制可用
立刻播放
循环和立体声定位不可用
同时播放不可用:您只能播放一个声音 时间
声音在设备扬声器上本地播放;它不使用 音频路由。
要控制一旦触发就停止声音,您需要使用其他API。对于高级API,请尝试 AVFoundation 框架中的 AVAudioPlayer 类。然后,您就可以通过touch down
等按钮连接事件以开始播放声音,还可以使用touch up inside
和touch drag outside
等事件来停止播放声音。
根据您正在做的其他事情,您可能会遇到也可能不会遇到性能问题。为了获得更好的性能(以及更多的代码编写), AudioUnits 将是首选。
使用 AVAudioPlayer 类的简短示例将是这样的 -
以下代码假定名为 AVAudioPlayer 的属性 loopPlayer ,在UIViewController子类中使用名为some_audio_loop_file.wav的文件进行初始化。
yourViewController.h
@property (nonatomic, strong) AVAudioPlayer *loopPlayer;
yourViewController.m
// set up loopPlayer property in for example viewDidLoad
NSURL* audioFileURL = [[NSBundle mainBundle] URLForResource:@"some_audio_loop_file" withExtension:@"wav"];
self.loopPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];
// called from a UIButton touch down event
-(IBAction)startAudioSample:(id)sender {
[self.loopPlayer play];
}
// called from a UIButton touch up inside and touch drag outside events
-(IBAction)stopAudioSample:(id)sender {
if (self.loopPlayer.isPlaying) {
[self.loopPlayer stop];
self.loopPlayer.currentTime = 0;
self.loopPlayer.numberOfLoops = -1;
[self.loopPlayer prepareToPlay];
}
答案 1 :(得分:1)
尝试:
-(IBAction)longPress:(UILongPressGestureRecognizer*)playsnare;
{
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundfileURLRef;
soundfileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"snare", CFSTR ("wav"), NULL);
UInt32 SoundID;
AudioServicesCreateSystemSoundID(soundfileURLRef, &SoundID);
AudioServicesPlaySystemSound(SoundID);
}
UILongPressGestureRecognizer是一个连续的事件识别器。你必须查看状态,看看这是事件的开始,中间还是结束,并采取相应的行动。也就是说,您可以在开始后离开所有事件,或者只根据需要查看运动。来自班级参考:
长按手势是连续的。当指定时间段(minimumPressDuration)按下允许的手指数(numberOfTouchesRequired)并且触摸不超出允许的移动范围(allowableMovement)时,手势开始(UIGestureRecognizerStateBegan)。每当手指移动时,手势识别器都会转换到更改状态,并且当任何手指抬起时,手势识别器会结束(UIGestureRecognizerStateEnded)。
现在你可以追踪像这样的状态
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
NSLog(@"UIGestureRecognizerStateEnded");
//Do Whatever You want on End of Gesture
}
else if (sender.state == UIGestureRecognizerStateBegan){
NSLog(@"UIGestureRecognizerStateBegan.");
//Do Whatever You want on Began of Gesture
}
}
答案 2 :(得分:-2)
创建属性
bool isPlaying
然后和你的IBAction函数一样
if(isPlaying){
stop();
}else{
play();
}