ios - 如何在按下按钮时播放音频并在手指离开同一按钮时立即停止?

标签 ios iphone objective-c ios7

我当前的按钮代码是。

-(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 insidetouch 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/

相关文章:

ios - NSUserDefaults 与 SegmentedControl 混淆

ios - 将栏按钮项目添加到 View Storyboard 中的导航栏

ios - willDisplayHeaderView 未在 TableViewController 中调用

objective-c - NSTextView查找栏的下一个关键 View

ios - 以编程方式创建可滚动下拉菜单(iOS/Swift)

ios - 使用 AFNetworking 同时加载 UITableViewCell 图像和文本标签时遇到问题

ios - JSON 解析在 IOS 中获取错误 NSErrorFailingURLKey

iphone - 在pdf iphone中突出显示一个字符串

ios - iOS 4 或 r5 可以在后台更新/更改播放项目吗?

iphone - 为什么在创建 UIWebView 时清除 NSUserDefaults 会导致 EXC_CRASH?