版本:
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.製作完成