Swift - Play a Sound

Aus Wikizone
Wechseln zu: Navigation, Suche

Links[Bearbeiten]

Swift - Snippets

Beispiele[Bearbeiten]

Xylophone[Bearbeiten]

Das Xylophon Beispiel basiert auf einem Storyboard, in dem wir verschiedene Schaltflächen haben deren Label C,D,E,usw ist. Dazu gibt es jeweils passende Sounds C.wav, D.wav, etc.

Wenn der User klickt, lesen wir das Label aus und spielen über die AVPAudioPlayer Objekt den Sound ab.

Hinweis: Zusätzlich legen wir den Alpha-Wert (Transparenz) des Sender Buttons für 0.2s auf halb.

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

    

}