我想创建一个带有两个按钮的简单应用程序,当您按下按钮时,会发出声音。但是当我尝试使用这个代码时,按下按钮时没有任何附加内容......
怎么了?
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBAction func button1(sender: AnyObject) {
var player1: AVAudioPlayer = AVAudioPlayer()
let audioPath1 = NSBundle.mainBundle().pathForResource("song1", ofType: "mp3")!
do {
try player1 = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath1))
} catch {
// Process error here
}
player1.play()
}
@IBAction func button2(sender: AnyObject) {
var player2: AVAudioPlayer = AVAudioPlayer()
let audioPath2 = NSBundle.mainBundle().pathForResource("song2", ofType: "mp3")!
do {
try player2 = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath2))
} catch {
// Process error here
}
player2.play()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
试试这个......
import UIKit
import AVFoundation
class TestAudio: UIViewController {
var ButtonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("FileName", ofType: "mp3")!)
var ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
try ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: nil)
} catch {
print("errorin do-try-catch")
}
}
@IBAction func PlayFirstAudio(sender: AnyObject) {
if ButtonAudioPlayer.playing == true {
ButtonAudioPlayer.stop()
} else {
ButtonAudioPlayer.play()
}
}
}