Last active
March 9, 2024 08:39
-
-
Save benigumocom/e6b3e2e3c339eb69cdb7a130bcd401f2 to your computer and use it in GitHub Desktop.
【Swift】SystemSoundID 一覧がないのですが 👉 https://android.benigumo.com/20240304/system-sound-id/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Observable final class Sound: Identifiable { | |
var id: SystemSoundID | |
var duration: Double | |
var playing: Bool | |
var valid: Bool { self.duration > 0.01 } | |
init(_ id: Int, _ duration: Double, _ playing: Bool) { | |
self.id = SystemSoundID(id) | |
self.duration = duration | |
self.playing = playing | |
} | |
} | |
struct SystemSoundGrid: View { | |
@State private var sounds: [Sound] = [] | |
@State private var scrollPositionId: SystemSoundID? | |
var body: some View { | |
let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 5) | |
VStack { | |
ScrollView { | |
LazyVGrid(columns: columns) { | |
ForEach(sounds) { sound in | |
Button { | |
sound.playing = true | |
AudioServicesPlaySystemSoundWithCompletion(sound.id) { | |
Thread.sleep(forTimeInterval: 0.1) | |
sound.playing = false | |
} | |
} label: { | |
VStack { | |
Text(String(sound.id)) | |
if sound.duration > Double.zero { | |
Text(String(format: "%.3f", sound.duration)) | |
} | |
} | |
.font(.system(size:10)) | |
.frame(maxWidth: .infinity) | |
.lineLimit(1) | |
} | |
.buttonStyle(.borderedProminent) | |
.disabled(sound.playing && sound.valid) | |
} | |
} | |
} | |
.padding() | |
.scrollPosition(id: $scrollPositionId) | |
.onChange(of: sounds.last?.id) { _, bottomId in | |
scrollPositionId = bottomId | |
} | |
.task { | |
await generate() | |
} | |
} | |
} | |
private func generate() async { | |
for i in 0 ..< 2000 { | |
sounds.append(Sound(i, Double.zero, true)) | |
let sound = await withCheckedContinuation { continuation in | |
let start = Date() | |
AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(i)) { | |
let elapsed = Date().timeIntervalSince(start) | |
continuation.resume(returning: Sound(i, elapsed, false)) | |
} | |
} | |
sounds.remove(at: sounds.count - 1) | |
if sound.valid { | |
sounds.append(sound) | |
} | |
} | |
} | |
} | |
#Preview { | |
SystemSoundGrid() | |
#if os(macOS) | |
.frame(width: 300, height: 300) | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment