スウィフトにはまったく新しいので、私の質問のnaivetyを許してください。
私は3つのボタンがそれぞれ異なるサウンドを演奏するとてもシンプルなアプリケーションを作りました。それは正常に動作しますが、コードは非常に効率的ではありません。なぜなら、各サウンドのプレーヤを作成してから、すべてのサウンドを再生するためにプレーヤのインスタンスを1つだけ使用する方法が不思議です。ここに私のコードは次のとおりです。スウィフト3倍AVAudioPlayer
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player1 = AVAudioPlayer()
var player2 = AVAudioPlayer()
var player3 = AVAudioPlayer()
@IBAction func playU3(_ sender: Any) {
player3.play()
}
@IBAction func playU2(_ sender: Any) {
player2.play()
}
@IBAction func playU1(_ sender: Any) {
player1.play()
}
override func viewDidLoad() {
super.viewDidLoad()
let audioPath3 = Bundle.main.path(forResource: "sound-3", ofType: "mp3")
let audioPath2 = Bundle.main.path(forResource: "sound-2", ofType: "mp3")
let audioPath1 = Bundle.main.path(forResource: "sound-1", ofType: "mp3")
do {
try player3 = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath3!))
try player2 = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath2!))
try player1 = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath1!))
} catch {
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
事前のおかげ
ご回答ありがとうございます。私はそれを少し修正しました.3つの 'audioPath'変数がすべての' playU1'関数などの内部ではなく、上に作成されています。 – Mauro74