ios播放声音和振动

首先需要引入头文件:

#import <AudioToolbox/AudioToolbox.h>

下面是方法

========================1.播放声音===============================

/**

 *  系统铃声播放完成后的回调
 */
void SystemSoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data)

{

   //通过传递的SoundID,当播放完声音时,结束掉声音

    AudioServicesDisposeSystemSoundID(sound_id);
}


// 播放接收到新消息时的声音
- (SystemSoundID)playNewMessageSound
{
    // 要播放的音频文件地址
    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"bundle的路径" withExtension:@"bundle"];
    NSURL *audioPath = [[NSBundle bundleWithURL:bundlePath] URLForResource:@"in" withExtension:@"caf"];
    // 创建系统播放声音,同时标识一个声音的ID
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
    // 注册声音,同时监听播放完后回调。
    AudioServicesAddSystemSoundCompletion(soundID,
                                          NULL, // NULL为主循环
                                          NULL, // 循环的模式为kCFRunLoopDefaultMode
                                          SystemSoundFinishedPlayingCallback, // 回调函数,并播放声音
                                          NULL // 为了data设置的,我们不需要设置,所以设置为 NULL
                                          );
    //播放声音
    AudioServicesPlaySystemSound(soundID);
    
    return soundID;

}


=========================2.播放振动==============================

// 震动
- (void)playVibration
{
    // Register the sound completion callback.
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate,
                                          NULL, // uses the main run loop
                                          NULL, // uses kCFRunLoopDefaultMode
                                          EMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
                                          NULL // for user data, but we don't need to do that in this case, so we just pass NULL
                                          );
    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值