用swift編寫ios應用-電子琴

版本:

swift 4,ios 11.2

1.界面設定
這裏寫圖片描述
2.配對按鈕
這裏寫圖片描述
3.編寫代碼

//  ViewController.swift
//  Xylophone
//
//  Created by lin on 2018/03/26.
//  Copyright © 2018年 lin. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioMatrix:[AVAudioPlayer?] = [AVAudioPlayer?]()

    @IBAction func playSound(_ sender: UIButton) {
        audioMatrix[sender.tag]?.stop()
        audioMatrix[sender.tag]?.play()
    }



    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 0...7{
            guard let path = Bundle.main.path(forResource: "\(i+1)", ofType: "mp3")else{
                audioMatrix.append(nil)
                return
            }
            let url = URL(fileURLWithPath: path)
            do{
                audioMatrix.append(try AVAudioPlayer(contentsOf: url))
            }catch{
                audioMatrix.append(nil)
            }
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

4.製作完成
這裏寫圖片描述

發佈了28 篇原創文章 · 獲贊 10 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章