iPhone应用开发之AudioServicesPlayerSystemSound音频播放

使用AudioToolbox framework.这个框架可以将比较短的声音注册到 system sound服务器上。被注册到systemsound服务上的声音称之为system sounds。它必须满足下面几个条件。

1、播放时间不能超过30秒。

2、数据必须是PCM或者IMA4流格式 

3、必须被打包成下面三个格式之一:Core Audio Format(.caf), waveform audio(.wav),或者Audio Interchange File(.aiff)

声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:


#import <AudioToolbox/AudioToolbox.h>

@interface MediaPlayerViewController :UIViewController

 IBOutletUIButton *audioButton;

  SystemSoundID shortSound;

@end


#import "MediaPlayerViewController.h"


- (id)init

{

    self = [super initWithNibName:@"MediaPlayerViewController"bundle:nil];

    

   if (self)

    {

       NSString *soundPath = [[NSBundle mainBundlepathForResource:@"Sound12"

                                                             ofType:@"aif"];

        // If this file is actually in the bundle...

       if (soundPath)

        {

            // Create a file URL with this path

           NSURL *soundURL = [NSURL fileURLWithPath:soundPath];

            

            // Register sound file located at that URL as a system sound

           OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL, 

                                                            &shortSound);

           if (err !=kAudioServicesNoError)

                NSLog(@"Could not load %@, error code: %d", soundURL, err);

        }

    }

    returnself;

}

这样就可以使用下面代码播放声音了:

- (IBAction)playShortSound:(id)sender

{

    AudioServicesPlaySystemSound(shortSound);

}

使用下面代码,还加一个震动的效果:

- (IBAction)playShortSound:(id)sender

{

    AudioServicesPlaySystemSound(shortSound);

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值