我想根据用户使用Map的速度来发出警告声音。当用户超过一定速度时,声音会起作用。但由于速度每秒都在变化,声音会重新开始。它不能正常工作。你能帮忙吗?我是软件新手。
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var imageLabel: UIImageView!
@IBOutlet weak var mapView: MKMapView!
var player : AVAudioPlayer!
var locationManager = CLLocationManager()
var lastSpeed = Int()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
imageLabel.isHidden = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let sonKonum : CLLocation = locations[locations.count - 1]
let konum = CLLocationCoordinate2D(latitude: sonKonum.coordinate.latitude, longitude: sonKonum.coordinate.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03)
let bolge = MKCoordinateRegion(center: konum, span: span)
mapView.setRegion(bolge, animated: true)
mapView.showsUserLocation = true
lastSpeed = Int(sonKonum.speed)
if lastSpeed >= 7 {
imageLabel.isHidden = false
player?.play()
} else {
imageLabel.isHidden = true
player?.stop()
}
print(sonKonum.speed)
}
func sesFonk() {
let url = Bundle.main.url(forResource: "yavas", withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: url!)
} catch {
print("hata")
}
}
}
1条答案
按热度按时间x8diyxa71#
每次更新位置时,执行以下代码:
如果用户速度足够快,则执行以下代码行:
导致声音重新启动的问题。
要解决这个问题,你应该在
player?.play()
还没有播放的时候才执行,你可以询问播放器是否处于“播放”状态: