在 iPhone SDK 中播放声音?

7

有没有使用AudioToolBox框架播放短声音的代码片段?如果您能与我和社区分享,我将不胜感激。我在其他地方查找的代码看起来都不太清晰。

谢谢!


你有特别想要的东西吗?AV Foundation框架是播放声音最简单的方法,但我猜你想要更多的东西? - Nathan S.
不,我只是想知道播放短声音的标准方法...许多人在网络上使用AudioToolBox...感谢您的回复 :) - esqew
3个回答

11

这是一个使用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 你可能需要将名称/类型更改为与您想要播放的文件相同。但是,我建议您提出一个新问题,并详细说明为什么它对您不起作用。 - Nathan S.
@NathanS:我修改了文件名。 - Vineesh TP
播放器应该在播放完成后立即释放。在这个例子中,它会在你听到旋律之前被终止。保持引用并在委托方法(AVAudioPlayerDelegate)中清除它。 - MikeR
MikeR,你错了,释放只会将引用计数减1。因此,当完成播放AVAudioPlayer对象时,它将减少最后一个引用计数,然后内存将被释放。当然,你也可以使用ARC并忘记这个问题。 - user2387149

7

我写了一个简单的Objective-C封装,围绕着 AudioServicesPlaySystemSound 和相关内容:

#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

居住地在这里。查看此问题以获取其他声音选项。


1
我建议人们使用@zoul的解决方案来处理系统声音(例如按钮点击等)。它支持的格式较少,但据说它的延迟更小,并且是文档中推荐用于处理系统声音的解决方案。另一方面,AVAudioPlayer非常适合播放音乐 - 但这不是原帖提出的问题。 :-) - Ivan Vučica

2

来源: AudioServices - iPhone Developer Wiki

AudioService 声音不受设备音量控制器的影响。即使手机处于静音模式,也会播放 Audio service 声音。只有通过进入设置 -> 声音 -> 铃声和提示音 才能将这些声音静音。

可以使用以下代码播放自定义系统声音:

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

在iPhone上调用震动功能
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

播放内置系统声音。
AudioServicesPlaySystemSound(1100);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接