Swift-停止avaudioplayer [英] Swift - Stop avaudioplayer
问题描述
我正在尝试将音板构建到应用程序中,并且找到了一种使用标签控制声音播放的有效方法.但是,我现在尝试在AVAudioPlayer
上集成一个可以与.stop()
方法一起使用的暂停按钮,但是我的当前代码出现错误:
I am trying to build a soundboard into an app and have figured out an efficient way of using tags to control playing the sounds. However I am now trying to integrate a pause button that can be used with the .stop()
method on the AVAudioPlayer
however I get an error with my current code:
EXC_BAD_ACCESS
这是我目前正在使用的任何想法吗?
This is what I am using at the moment, any ideas?
import UIKit
import AVFoundation
let soundFilenames = ["sound","sound2","sound3"]
var audioPlayers = [AVAudioPlayer]()
class SecondViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
for sound in soundFilenames {
do {
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
audioPlayers.append(audioPlayer)
} catch {
//Catch error thrown
audioPlayers.append(AVAudioPlayer())
}
}
}
@IBAction func buttonPressed(sender: UIButton) {
let audioPlayer = audioPlayers[sender.tag]
audioPlayer.play()
}
@IBAction func stop(sender: UIButton) {
audioPlayer.stop()
}
}
推荐答案
停止功能中的audioPlayer不是正在播放的播放器.您应该在buttonPressed函数中分配它.
Your audioPlayer in stop function is not the playing player. You should assign it in buttonPressed function.
@IBAction func buttonPressed(sender: UIButton) {
audioPlayer = audioPlayers[sender.tag]
audioPlayer.play()
}
顺便说一句,您可以将audioPlayer标记为?"属性,则在初始化此Controller时会更有效率.
By the way, You can mark audioPlayer as a "?" property, it will be more efficient when init this Controller.
class SecondViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
let enableMuiltPlayers = false
....
@IBAction func buttonPressed(sender: UIButton) {
if sender.tag < audioPlayers.count else {
print("out of range")
return
}
if enableMuiltPlayers {
audioPlayers[sender.tag].play()
} else {
audioPlayer?.stop()
//set the current playing player
audioPlayer = audioPlayers[sender.tag]
audioPlayer?.play()
}
}
@IBAction func stop(sender: UIButton) {
let wantToStopAll = false
if enableMuiltPlayers && wantToStopAll {
stopAll()
} else {
audioPlayer?.stop()
}
audioPlayer = nil
}
}
停止所有操作:
fun stopAll() {
for player in audioPlayers {
player.stop()
}
}
这篇关于Swift-停止avaudioplayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!