Спасибо за посещение этого вопроса.
Я недавно начал изучать Swift. Я делаю аудиоплеер я sh приложение.
NextButton работает только пару раз, а затем просто отключается. Я пытаюсь сделать массив l oop снова и снова, если нажимается следующая кнопка. Таким образом, это означает, что когда я нажимаю кнопку «следующий», он будет go переходить к следующему треку, а если треки из массива завершатся, он будет воспроизводить все треки снова.
Все, что я пытаюсь добиться, чтобы «следующая» кнопка работала без остановок.
Массив и аудиоплеер:
let sound1 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!)
let sound2 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "2", ofType: "mp3")!)
let sound3 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "3", ofType: "mp3")!)
lazy var soundArray: [NSURL] = [sound1, sound2, sound3]
var audioPlayer = AVAudioPlayer()
var run = true
var currentIndex = 0
func playRandomSound() {
let randNo = Int(arc4random_uniform(UInt32(soundArray.count)))
if run == true{
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: soundArray[randNo] as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
nextButton:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
currentIndex = indexPath.row
}
@IBAction func nextButton(_ sender: Any) {
audioPlayer.stop()
print("Audio did stop")
if currentIndex + 1 < soundArray.count {
currentIndex += 1
playRandomSound()
}
}
Полный код:
import UIKit
import AVFoundation
extension UILabel {
func pushUp(_ text: String?) {
let animation:CATransition = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.push
animation.subtype = CATransitionSubtype.fromTop
animation.duration = 1
self.layer.add(animation, forKey: CATransitionType.push.rawValue)
self.text = text
}
}
class HideShow: UIViewController, AVAudioPlayerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var moveOn: UILabel!
@IBOutlet weak var Logo: UILabel!
@IBOutlet weak var BGimage: UIImageView!
@IBOutlet weak var nextButton2: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var LayDown: UILabel!
@IBOutlet weak var audioChanger: UIButton!
@IBOutlet weak var buttonView: UIView!
let notification = NotificationCenter.default
let toImage = UIImage(named:"BG2.jpeg")
@IBAction func buttonTapped(_ sender: UIButton){
UIView.animate(withDuration: 2) {
self.LayDown.alpha = 1
}
UIView.transition(with: self.BGimage,
duration: 1,
options: .transitionCrossDissolve,
animations: { self.BGimage.image = self.toImage },
completion: nil)
LayDown.pushUp("CLOSE YOUR EYES")
self.nextButton.isHidden = true
self.nextButton2.isHidden = false
}
let sound1 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!)
let sound2 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "2", ofType: "mp3")!)
let sound3 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "3", ofType: "mp3")!)
lazy var soundArray: [NSURL] = [sound1, sound2, sound3]
var audioPlayer = AVAudioPlayer()
var run = true
var currentIndex = 0
func playRandomSound() {
let randNo = Int(arc4random_uniform(UInt32(soundArray.count)))
if run == true{
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: soundArray[randNo] as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
@IBAction func buttonTapped2(_ sender: Any) {
UIView.animate(withDuration: 1) {
self.nextButton2.alpha = 0
self.LayDown.alpha = 0
self.nextButton.alpha = 0
self.BGimage.alpha = 0
self.moveOn.alpha = 0
self.Logo.alpha = 0
self.audioChanger.isHidden = false
self.buttonView.isHidden = false
}
playRandomSound()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
currentIndex = indexPath.row
}
@IBAction func nextButton(_ sender: Any) {
audioPlayer.stop()
print("Audio did stop")
if currentIndex + 1 < soundArray.count {
currentIndex += 1
playRandomSound()
}
}
}
Дайте мне знать, если у вас есть какие-либо вопросы, Заранее спасибо! :)) 1018 *