ios - 如何在 Swift 中按一次按钮后播放歌曲列表
问题描述
我知道如何在您按下屏幕上的按钮时播放一首歌曲,而不是一组歌曲,其中一首歌曲在歌曲完成后自动播放,直到播放完数组中的所有歌曲。
有人提到使用 AVQueuePlayer 但我们中的无数人不知道如何实现。你们能提供一个很好的示例代码来说明如何使用它吗?
我按照此视频中的代码在您点击按钮时播放一首歌曲 - https://www.youtube.com/watch?v=2kflmGGMBOA
var myQueuePlayer: AVQueuePlayer?
var avItems: [AVPlayerItem] = []
func audio () {
var items: [String] = ["one", "two", "three", "four", "five"]
items.shuffle()
for clip in items {
guard let url = Bundle.main.url(forResource: clip, withExtension: ".mp3") else {
// mp3 file not found in bundle - so crash!
fatalError("Could not load \(clip).mp3")
}
avItems.append(AVPlayerItem(url: url))
//button.isHidden = true
}
}
@IBAction func didTapButton() {
audio()
if myQueuePlayer == nil {
// instantiate the AVQueuePlayer with all avItems
myQueuePlayer = AVQueuePlayer(items: avItems)
print("pup1")
print(myQueuePlayer!.rate)
} else {
// stop the player and remove all avItems
myQueuePlayer?.removeAllItems()
// add all avItems back to the player
avItems.forEach {
myQueuePlayer?.insert($0, after: nil)
}
}
// seek to .zero (in case we added items back in)
myQueuePlayer?.seek(to: .zero)
// start playing
myQueuePlayer?.play()
}
解决方案
你真的应该很容易找到这个,但这里有一个非常简单的例子:
import AVFoundation
class TestAVQueuViewController: UIViewController {
var myQueuePlayer: AVQueuePlayer?
var avItems: [AVPlayerItem] = []
override func viewDidLoad() {
super.viewDidLoad()
// assuming I have 4 .mp3 files in the bundle, named:
let mySongs: [String] = [
"clip1", "clip2", "clip3", "clip4",
]
for clip in mySongs {
guard let url = Bundle.main.url(forResource: clip, withExtension: ".mp3") else {
// mp3 file not found in bundle - so crash!
fatalError("Could not load \(clip).mp3")
}
avItems.append(AVPlayerItem(url: url))
}
}
@IBAction func didTap(_ sender: Any) {
// if first time
if myQueuePlayer == nil {
// instantiate the AVQueuePlayer with all avItems
myQueuePlayer = AVQueuePlayer(items: avItems)
} else {
// stop the player and remove all avItems
myQueuePlayer?.removeAllItems()
// add all avItems back to the player
avItems.forEach {
myQueuePlayer?.insert($0, after: nil)
}
}
// seek to .zero (in case we added items back in)
myQueuePlayer?.seek(to: .zero)
// start playing
myQueuePlayer?.play()
}
}
编辑
更新了代码以演示在点击按钮时播放剪辑,并在进一步点击按钮时重新启动剪辑。
推荐阅读
- c# - Xamarin 表单从 Firebase 获取所有值
- javascript - nodejs puppeteer无法下载URL中带有特殊字符的图像文件
- html - CSS样式实现曲线圆
- docusignapi - 如何在没有“EnvelopeRecipients::List”的情况下使用 Docusign API 获得拒绝原因
- amazon-web-services - Terraform - 当它是端点服务的一部分时,无法删除负载均衡器
- java - 如何在 vscode 中设置 launch.json 中的默认 java 配置,以使 vscode 在每次运行应用程序时停止要求我指定主类?
- python - 获取_tkinter.TclError:tkinter中的未知选项“-relief”错误
- java - 为什么这个常量声明在 Java 中不起作用?
- firebase - 如何在 Web 应用程序中处理日常计算(Google Firebase/NestJS)
- amazon-web-services - AWS SES 554-没有适用于 web.de 和 GMX 电子邮件地址的 SMTP 服务