포스트

Xylophone (2)

Xylophone에서 각 버튼을 눌렀을때 다음과같이 흐려졌다가 다시 밝아지게 해보자.

그리고 눌렀을때 Console에 start가 바로 출력이 되었다가. 0.2초 후에 End가 나오게 해보자.


before

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func keyPressed(_ sender: UIButton) {
        
        //print(sender.currentTitle)
        
        playSound(soundName: sender.currentTitle!)
    }
    
    func playSound(soundName: String) {
        let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        
        player.play()
                
    }
}


after

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func keyPressed(_ sender: UIButton) {
        
        //print(sender.currentTitle)
        
        playSound(soundName: sender.currentTitle!)
        print("Start")
        sender.alpha = 0.5
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            print("End")
            sender.alpha = 1.0
         }
    }
    
    func playSound(soundName: String) {
        let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
                
    }
    
    
}


1
2
3
4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            print("End")
            sender.alpha = 1.0
         }

위와 같은 코드를 썼다. 0.2초뒤에 end를 출력하고 투명도(alpha)를 1.0으로 원복하는것이다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.