我当前的按钮代码是。
-(IBAction)playsnare;
{
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundfileURLRef;
soundfileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"snare", CFSTR ("wav"), NULL);
UInt32 SoundID;
AudioServicesCreateSystemSoundID(soundfileURLRef, &SoundID);
AudioServicesPlaySystemSound(SoundID);
}
我可以添加什么来使按钮在按下时播放并在未按下时停止。
最佳答案
您播放音频样本的实现不允许这样做。由于您使用的是 AudioToolbox 框架中的 AudioServicesPlaySystemSound,因此一旦触发音频样本就无法停止播放。您只能在播放完毕后才能收到回调。
这种播放声音的方式还有其他限制(摘自文档)
In addition, when you use the AudioServicesPlaySystemSound function:
Sounds play at the current system audio volume, with no programmatic volume control available
Sounds play immediately
Looping and stereo positioning are unavailable
Simultaneous playback is unavailable: You can play only one sound at a time
The sound is played locally on the device speakers; it does not use audio routing.
要控制声音一旦触发就停止,您需要使用另一个 API。对于高级 API,请尝试 AVFoundation 框架中的 AVAudioPlayer 类。然后,您将能够连接按钮上的事件,例如 touch down
来开始播放声音,还可以连接诸如 touch up inside
和 touch Drag 等事件外部
停止声音播放。
您可能会也可能不会遇到性能问题,具体取决于您正在执行的其他操作。为了获得更好的性能(以及更多的代码编写),AudioUnits 将是首选。
使用 AVAudioPlayer 类的简短示例如下 -
The following code assumes a property of type AVAudioPlayer named loopPlayer that is initialised with a file called some_audio_loop_file.wav in a UIViewController sub-class.
你的ViewController.h
@property (nonatomic, strong) AVAudioPlayer *loopPlayer;
你的ViewController.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];
}
关于ios - 如何在按下按钮时播放音频并在手指离开同一按钮时立即停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21643007/