让iPhone振动

时间:2011-01-18 14:04:51

标签: ios cocoa-touch avfoundation vibration

如何将iPhone设置为振动一次?

例如,当玩家失去生命或游戏结束时,iPhone应振动。

12 个答案:

答案 0 :(得分:398)

来自“iPhone Tutorial: Better way to check capabilities of iOS devices”:

有两个看似相似的函数采用参数kSystemSoundID_Vibrate

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
  

这两项功能都会震动iPhone。但是,当你使用第一个   在不支持振动的设备上运行,它会发出哔哔声   声音。另一方面,第二个功能没有任何作用   不受支持的设备。所以,如果你要振动设备   常识说,连续,作为警报,使用功能2。

首先,在Build Phases中将AudioToolbox框架AudioToolbox.framework添加到目标。

然后,导入此头文件:

#import <AudioToolbox/AudioServices.h>

答案 1 :(得分:45)

Swift 2.0 +

AudioToolbox现在将kSystemSoundID_Vibrate显示为SystemSoundID类型,因此代码为:

import AudioToolbox.AudioServices

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)

而不是必须通过额外的演员步骤

(Props to @Dov)

原始答案(Swift 1.x)

而且,这就是你在 Swift 上的表现(如果你遇到了和我一样的麻烦)

链接AudioToolbox.framework(转到您的项目,选择目标,构建阶段,链接二进制文件库,在那里添加库)

完成后:

import AudioToolbox.AudioServices

// Use either of these
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

俗气的是,SystemSoundID基本上是typealias(花式快速typedefUInt32kSystemSoundID_Vibrate是常规{{} 1}}。编译器在尝试从Int转换为Int时会出错,但错误读作“无法转换为SystemSoundID”,这令人困惑。为什么苹果不能让它成为一个Swift枚举超出我的范围。

@ aponomarenko's详细介绍,我的答案仅适用于那里的Swifters。

答案 2 :(得分:35)

一种简单的方法是使用音频服务:

#import <AudioToolbox/AudioToolbox.h> 
...    
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

答案 3 :(得分:28)

对于以某种方式关闭振动的设备,我遇到了很大的麻烦,但我们需要它无论如何都要工作,因为它对我们的应用程序运行至关重要,因为它只是文档化方法调用的整数,它会通过验证。所以我尝试了一些声音,这些声音不在这里有详细记录的声音:TUNER88/iOSSystemSoundsLibrary

我偶然发现1352,无论静音开关或设备(Settings->vibrate on ring, vibrate on silent)上的设置如何,它都能正常工作。

- (void)vibratePhone;
{
     if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
     {
         AudioServicesPlaySystemSound (1352); //works ALWAYS as of this post
     }
     else
     {
          // Not an iPhone, so doesn't have vibrate
          // play the less annoying tick noise or one of your own
          AudioServicesPlayAlertSound (1105);
     }
}

答案 4 :(得分:24)

  

重要提示:未来弃权的警示。

     

iOS 9.0 开始, API 的功能描述为:

AudioServicesPlaySystemSound(inSystemSoundID: SystemSoundID)
AudioServicesPlayAlertSound(inSystemSoundID: SystemSoundID)

包括以下注释:

This function will be deprecated in a future release.
Use AudioServicesPlayAlertSoundWithCompletion or  
AudioServicesPlaySystemSoundWithCompletion instead.
  

正确的方法是使用以下任何一种:

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
 //your callback code when the vibration is done (it may not vibrate in iPod, but this callback will be always called)
}
  

请记得import AVFoundation

答案 5 :(得分:5)

如果你正在使用Xamarin(monotouch)框架,只需调用

即可
SystemSound.Vibrate.PlayAlertSound()

答案 6 :(得分:5)

在我旅行中,我发现如果您在录制音频时尝试以下任一操作,即使设备已启用,设备也不会振动。

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

在测量设备运动的特定时间调用我的方法。我不得不停止录音,然后在振动发生后重新开始。

看起来像这样。

-(void)vibrate {
    [recorder stop];
    AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
    [recorder start];
}

recorder是AVRecorder实例。

希望这可以帮助以前遇到过同样问题的其他人。

答案 7 :(得分:4)

在iOS 10和更新的iPhone上,您还可以使用触觉API。此触觉反馈比AudioToolbox API更柔和。

对于您的GAME OVER场景,重要的UI影响反馈应该是合适的。

UIImpactFeedbackGenerator(style: .heavy).impactOccurred()

您可以使用other haptic feedback styles

答案 8 :(得分:2)

对于iPhone 7/7 Plus或更高版本,请使用这三个Haptic反馈API。

可用的API

有关通知:

let generator = UINotificationFeedbackGenerator()
generator.notificationOccured(style: .error)

可用的样式为.error.success.warning。每个人都有其独特的感觉。
摘自docs

  

具体的UIFeedbackGenerator子类,它创建触觉来传达成功,失败和警告。

简单振动:

let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccured()

可用的样式为.heavy.medium.light。这些是具有不同程度的“硬度”的简单振动。
摘自docs

  

一个具体的UIFeedbackGenerator子类,它创建触觉来模拟物理影响

用于用户选择项目时

let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()

这是所有触觉中最不引人注意的,因此最适合不应将触觉取代应用程序体验的情况。
摘自docs

  

具体的UIFeedbackGenerator子类,它创建触觉来指示选择的变化。

注释

使用这些API时,需要记住几件事。

说明A

您实际上没有创建触觉。请求系统生成触觉。系统将根据以下内容进行决定:

  • 如果设备上有触觉功能(在这种情况下是否具有Taptic Engine)
  • 该应用是否可以录制音频(录制过程中不会产生触觉,以防止不必要的干扰)
  • 是否在系统设置中启用了触觉。

因此,如果不可能,系统将静默忽略您对触觉的请求。如果是由于设备不受支持所致,则可以尝试以下操作:

func haptic() {
    // Get whether the device can generate haptics or not
    // If feedbackSupportLevel is nil, will assign 0
    let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0

    switch feedbackSupportLevel { 
    case 2:
        // 2 means the device has a Taptic Engine
        // Put Taptic Engine code here, using the APIs explained above

    case 1: 
    // 1 means no Taptic Engine, but will support AudioToolbox
    // AudioToolbox code from the myriad of other answers!

    default: // 0
        // No haptic support
        // Do something else, like a beeping noise or LED flash instead of haptics
    }

将注释替换为switch-case语句,此触觉生成代码将可移植到其他iOS设备。它将产生最高级别的触觉。

注释B

  • 由于生成触觉是硬件级别的任务,因此当您调用触觉生成代码与生成触觉代码之间可能会有延迟>实际上会发生。因此,Taptic Engine API均具有prepare()方法,使其处于就绪状态。使用“游戏结束”示例:您可能知道游戏即将结束,原因是用户的HP极低,或者附近有危险的怪物。
  • 如果您在几秒钟内没有生成触觉,则Taptic Engine将返回到空闲状态(以节省电池寿命)


在这种情况下,准备Taptic Engine将创造出更高质量,响应速度更快的体验。

例如,假设您的应用使用平移手势识别器来更改可见世界的一部分。您希望在用户“环视” 360度时生成触觉。这是使用prepare()的方法:

@IBAction func userChangedViewablePortionOfWorld(_ gesture: UIPanGestureRecogniser!) {

    haptic = UIImpactFeedbackGenerator(style: .heavy)

    switch gesture.state {
        case .began:
            // The user started dragging the screen.
            haptic.prepare()

        case .changed:
            // The user trying to 'look' in another direction
            // Code to change viewable portion of the virtual world

            if virtualWorldViewpointDegreeMiddle = 360.0 { 
                haptic.impactOccured()
            }

        default:
            break

} 

答案 9 :(得分:1)

在斯威夫特:

select  count(c.c_no) as contacts_count, count(u_no) as user_count, a.* 
from accounts a
LEFT JOIN users u on u.a_no = a.a_no and u_status = 1
LEFT JOIN IDP1.contacts c on c.a_no = a.a_no and c_status = 1
where a_status = 1
group by a_no

答案 10 :(得分:0)

就我而言,我正在使用AVCaptureSession。 AudioToolbox处于项目的构建阶段,它已导入但仍无法正常工作。为了使其工作,我在振动之前停止了会话并在此之后继续。

#import <AudioToolbox/AudioToolbox.h>
...
@property (nonatomic) AVCaptureSession *session;
...
- (void)vibratePhone;
{
  [self.session stopRunning];
     NSLog(@"vibratePhone %@",@"here");
    if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
    {
        AudioServicesPlaySystemSound (kSystemSoundID_Vibrate); 
    }
    else
    {
        AudioServicesPlayAlertSound (kSystemSoundID_Vibrate);
    }
  [self.session startRunning];
}

答案 11 :(得分:-5)

您可以使用

1)AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

适用于iPhone和少数较新的iPod。

2)AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

适用于iPad。