Swift 的声音和振动

声音

1
2
3
4
5
6
7
8
9
import AVFoundation

class SoundPlayer {
var soundIdIndex = 1000
func playSound() {
let soundID = SystemSoundID(soundIdIndex)
AudioServicesPlaySystemSound(soundID)
}
}

使用方法为

1
2
let player = SoundPlayer()
player.playSound()

声音 id 可参考 iOSSystemSoundsLibrary

振动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import AVFoundation

enum Vibration {

case error
case success
case warning
case light
case medium
case heavy
@available(iOS 13.0, *)
case soft
@available(iOS 13.0, *)
case rigid
case selection

public func vibrate() {
switch self {
case .error:
UINotificationFeedbackGenerator().notificationOccurred(.error)
case .success:
UINotificationFeedbackGenerator().notificationOccurred(.success)
case .warning:
UINotificationFeedbackGenerator().notificationOccurred(.warning)
case .light:
UIImpactFeedbackGenerator(style: .light).impactOccurred()
case .medium:
UIImpactFeedbackGenerator(style: .medium).impactOccurred()
case .heavy:
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
case .soft:
if #available(iOS 13.0, *) {
UIImpactFeedbackGenerator(style: .soft).impactOccurred()
}
case .rigid:
if #available(iOS 13.0, *) {
UIImpactFeedbackGenerator(style: .rigid).impactOccurred()
}
case .selection:
UISelectionFeedbackGenerator().selectionChanged()

}
}
}

使用方法

1
Vibration.rigid.vibrate()

Swift 的声音和振动
https://wonderhoi.com/2024/01/19/Swift-的声音和振动/
作者
wonderhoi
发布于
2024年1月19日
许可协议