问题
I want my swift code to call the playSound and play the sound based for the duration of each item in array playamount. So I want the user to play the sound for the first time for 10 seconds then play the sound starting at the beginning for 20 and then the same thing for 30 seconds. So the sound always starts at the beginning each time it is called.
import UIKit; import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
func playSound() {
let url = Bundle.mainBundle().URLForResource("rock", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
var playAmount : [Int] = [10,20,30]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
回答1:
class ViewController: UIViewController {
var player: AVAudioPlayer?
var currentIndex: Int = 0
func runMusicBox() {
guard !playAmount.isEmpty else { return }
currentIndex = 0
newTimerForIndex(index: 0)
}
func newTimerForIndex(index: Int) {
player?.prepareToPlay()
player?.play()
Timer.scheduledTimer(withTimeInterval: Double(playAmount[index]), repeats: false) { timer in
self.player?.stop()
if self.currentIndex + 1 < self.playAmount.count {
self.currentIndex += 1
self.newTimerForIndex(index: self.currentIndex)
} else {
self.player?.stop()
}
}
}
func playSound() {
let url = Bundle.mainBundle().URLForResource("rock", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
runMusicBox()
} catch let error as NSError {
print(error.description)
}
}
var playAmount : [Int] = [10,20,30]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Hi, can you try this code. Here I have a timer, and when one stops, then we check if we have another element in the array and will run a new timer. The Timer is working, but i didn;t check the player. if it works as expected - it should work for you
来源:https://stackoverflow.com/questions/63494572/play-swift-sound-based-on-each-duration-of-i-time-in-array