Home > OS >  AVAudioPlayer keeps restarting
AVAudioPlayer keeps restarting

Time:01-20

I want to make a warning sound according to the speed of the user using the map. When the user is above a certain speed, the sound works. But since the speed changes every second, it starts again. It's not working properly. Can you help with this? I'm new to software.

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")
        }
    }
}

CodePudding user response:

Every time the location gets updated you execute this code:

if lastSpeed >= 7 {
    imageLabel.isHidden = false
    player?.play()
} else {
    imageLabel.isHidden = true
    player?.stop()
}

and if the user is fast enough you execute this line:

player?.play()

that is causing your issue of the sound being restarted.

To solve this you should execute player?.play() only when it doesn´t play allready. You can ask the player if it is in "playing" state:

if lastSpeed >= 7 {
    if !(player?.isPlaying ?? true) {
        imageLabel.isHidden = false
        player?.play()
    }
} else {
    imageLabel.isHidden = true
    player?.stop()
}
  • Related