Swift - Play a Sound
Aus Wikizone
Version vom 29. Dezember 2022, 18:40 Uhr von 134.3.86.14 (Diskussion) (Die Seite wurde neu angelegt: „== Beispiele == === Xylophone === <syntaxhighlight lang="Swift"> // // ViewController.swift // Xylophone // // Created by Angela Yu on 28/06/2019. // Copyr…“)
Beispiele
Xylophone
//
// ViewController.swift
// Xylophone
//
// Created by Angela Yu on 28/06/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import UIKit
import AVFoundation
import Dispatch
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func keyPressed(_ sender: UIButton) {
let soundName:String = sender.currentTitle!
// Note: currentTitle is defined as type optional string,
// meaning there are cases when no title exists (value = nil)
// by adding ! we say "don't worry - we checked that the input
// is guaranteed a string. Another way to be safe would be a guard:
// guard let soundName:String = sender.currentTitle else {return}
// a guard checks the value and would go to the else function
// and therefore return in this case if the value is nil
self.playAudioFile(soundName:soundName)
sender.alpha = 0.5
// Delay code execution for 0.2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// Code to be executed after the delay
sender.alpha = 1.0
}
}
var audioPlayer: AVAudioPlayer?
func playAudioFile(soundName:String) {
guard let url = Bundle.main.url(forResource: soundName, withExtension: "wav") else { return }
do {
// Change defaults to category playback (play sound even if phone is silenced)
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(
contentsOf: url,
fileTypeHint: AVFileType.wav.rawValue
)
guard let audioPlayer = audioPlayer else { return }
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
}