arrays - 根据数组中 I 时间的每个持续时间播放快速声音
问题描述
我希望我的快速代码调用 playSound 并根据数组 playamount 中每个项目的持续时间播放声音。所以我希望用户第一次播放声音 10 秒,然后从头开始播放声音 20 秒,然后同样的声音 30 秒。因此,每次调用声音时,声音总是从开头开始。
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.
}
}
解决方案
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.
}
}
嗨,你可以试试这个代码。这里我有一个计时器,当一个计时器停止时,我们检查数组中是否还有另一个元素,然后运行一个新的计时器。计时器正在工作,但我没有检查播放器。如果它按预期工作 - 它应该适合你
推荐阅读
- python - 无法从“tensorflow.keras.layers.experimental.preprocessing”导入名称“CenterCrop”
- python - 如何在 opemnmt-py 中将字符串转换为路径
- swift - BindableObject 和 ObservableObject 有什么区别?
- mongodb - 深度嵌套数组中的 mongodb $slice 元素
- swiftui - 在 SwiftUI 中设置导航栏项目样式
- javascript - 结束点击的功能
- javascript - RTL 密码复制/粘贴问题
- python-3.x - 错误处理包 python3-pip (--configure) ubuntu 20.04 焦点窝
- java - 自定义警报对话框视图不显示动态设置的内容
- android - 删除毕加索在角落顶部显示蓝色/绿色/红色三角形