可以通过以下步骤实现:
import SwiftUI
import AVFoundation
struct BlinkingBellView: View {
@State private var isAnimating = false
let audioPlayer = AVAudioPlayer()
var body: some View {
Image("bell") // 替换为你的铃声图片
.resizable()
.frame(width: 100, height: 100)
.opacity(isAnimating ? 0.5 : 1)
.animation(Animation.easeInOut(duration: 0.5).repeatForever())
.onAppear {
startAnimating()
playSound()
}
.onDisappear {
stopAnimating()
stopSound()
}
}
func startAnimating() {
isAnimating = true
}
func stopAnimating() {
isAnimating = false
}
func playSound() {
guard let soundURL = Bundle.main.url(forResource: "bell_sound", withExtension: "mp3") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
audioPlayer.play()
} catch {
print("Failed to play sound: \(error)")
}
}
func stopSound() {
audioPlayer.stop()
}
}
BlinkingBellView
来显示闪烁的铃声动画:struct ContentView: View {
var body: some View {
VStack {
Text("Welcome to SwiftUI")
.font(.largeTitle)
.padding()
BlinkingBellView()
}
}
}
这样,当你运行应用程序时,你将看到一个闪烁的铃声动画在界面上显示,并且会播放铃声音频文件。你可以根据需要自定义动画的持续时间、重复次数、铃声图片和音频文件。
注意:为了使铃声音频文件正常播放,确保将铃声音频文件(例如bell_sound.mp3
)添加到你的项目资源中,并将其替换为playSound()
函数中的文件名。
领取专属 10元无门槛券
手把手带您无忧上云