代码之家  ›  专栏  ›  技术社区  ›  esqew

在iphone sdk中播放声音?

  •  7
  • esqew  · 技术社区  · 14 年前

    有没有人有一个片段,使用音频工具箱框架,可以用来播放一个简短的声音?如果你能和我和社区其他人分享,我将不胜感激。我看过的其他地方似乎都不太清楚他们的代码。

    谢谢!

    3 回复  |  直到 12 年前
        1
  •  11
  •   Nathan S.    14 年前

    下面是一个使用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”的文件。因为我经常播放这个声音,所以我会把它放在周围,以便以后播放,而不是释放它。

        2
  •  7
  •   Community CDub    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
    

    生活 here . 有关其他声音选项,请参见 this question .

        3
  •  2
  •   Govind    12 年前

    来源 : AudioServices - iPhone Developer Wiki

    音频服务声音和设备音量控制器无关。即使手机处于静音模式,也会播放音频服务声音。这些声音只能通过 设置 -gt; 声音 -gt; 铃声和警报 .

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

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

    调用iphone中的振动

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    

    播放内置系统声音。

    AudioServicesPlaySystemSound(1100);