【问题标题】:Playing sounds in iPhone SDK?在 iPhone SDK 中播放声音?
【发布时间】:2010-03-20 14:56:02
【问题描述】:

谁有使用AudioToolBox框架的sn-p可以用来播放短音?如果您与我和社区的其他人分享它,我将不胜感激。我看过的其他所有地方的代码似乎都不太清楚。

谢谢!

【问题讨论】:

  • 您有什么特别需要的吗? AV Foundation 框架是播放声音的最简单方法,但我想您还想要更多?
  • 不,我只是想知道播放短声音的标准方式...网上很多人都在使用 AudioToolBox...感谢您的回复:)

标签: iphone xcode iphone-sdk-3.0 audio


【解决方案1】:

这是一个使用 AVAudioPlayer 的简单示例:

-(void)PlayClick
{
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                               pathForResource:@"click"
                                               ofType:@"caf"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click play];
    [click release];
}

这假定主包中存在一个名为“click.caf”的文件。由于我经常播放这种声音,我实际上将它保留在以后播放而不是释放它。

【讨论】:

  • @VineeshTP 您可能需要将名称/类型更改为与您要播放的文件相同。但是,我建议提出一个新问题并详细说明为什么它不适合您。
  • @NathanS.:我更改了文件文件名。
  • 播放器应该在播放完后立即释放。在这个例子中,它会在你听到旋律之前被杀死。保留引用并在委托方法中清理它(AVAudioPlayerDelegate)
  • MikeR 你错了,释放只会减少1的引用计数。因此当播放完AVAudioPlayer对象会减少最后的引用计数,然后内存将被释放。当然,您可以随时使用 ARC 而忘记这一点。
【解决方案2】:

我围绕AudioServicesPlaySystemSound 和朋友编写了一个简单的Objective-C 包装器:

#import <AudioToolbox/AudioToolbox.h>

/*
    Trivial wrapper around system sound as provided
    by Audio Services. Don’t forget to add the Audio
    Toolbox framework.
*/

@interface Sound : NSObject
{
    SystemSoundID handle;
}

// Path is relative to the resources dir.
- (id) initWithPath: (NSString*) path;
- (void) play;

@end

@implementation Sound

- (id) initWithPath: (NSString*) path
{
    [super init];
    NSString *resourceDir = [[NSBundle mainBundle] resourcePath];
    NSString *fullPath = [resourceDir stringByAppendingPathComponent:path];
    NSURL *url = [NSURL fileURLWithPath:fullPath];

    OSStatus errcode = AudioServicesCreateSystemSoundID((CFURLRef) url, &handle);
    NSAssert1(errcode == 0, @"Failed to load sound: %@", path);
    return self;
}

- (void) dealloc
{
    AudioServicesDisposeSystemSoundID(handle);
    [super dealloc];
}

- (void) play
{
    AudioServicesPlaySystemSound(handle);
}

@end

生活在here。有关其他声音选项,请参阅this question

【讨论】:

  • 我建议人们使用@zoul 的系统声音解决方案(按钮点击等)。它支持的格式较少,但它的滞后性应该较小,并且它是用于系统声音的首选文档解决方案。另一方面,AVAudioPlayer 非常适合播放音乐 - 但这不是原始海报所要求的。 :-)
【解决方案3】:

来源AudioServices - iPhone Developer Wiki

AudioService 声音与设备音量控制器无关。即使手机处于静音模式,也会播放音频服务声音。这些声音只能通过设置 -> 声音 -> 铃声和提醒来静音。

自定义系统声音可以通过以下代码播放:

CFBundleRef mainbundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(mainbundle, CFSTR("tap"), CFSTR("aif"), NULL);
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject);

在 iPhone 中调用振动

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

播放内置系统声音。

AudioServicesPlaySystemSound(1100);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    相关资源
    最近更新 更多