我正在重新学习如何编程,并尝试制作交互式成绩单文档。
我真的可以使用一些指针来了解如何在本地文件的 SwiftUI 文本视图中理想地显示 webVTT 文件的文本。
其次,可能更重要的是,在这个过程中的这一步,我想知道如何解析带有文本的时间戳,以便我可以将其同步到正在播放的音频。
我发现了这个令人惊奇的例子https://www.reddit.com/r/iOSProgramming/comments/10y0jcp/i_recreated_the_new_progressing_style_lyrics_from/作者:Reddit u/mageshsridhar,虽然这不是我希望实现的目标,但它显示了与音频同步的文本.
我正在寻找一个您可以阅读的文本页面,该文本来自 webVTT 文件。如果您点击文本上的任意位置,它将立即开始播放该句子的音频。相反,如果您正在阅读,我希望它也突出显示当前正在播放的文本或句子。
使用 Reddit 中的 u/mageshsridhar 示例,我可以手动添加文本并且它可以工作。
我到底如何编码才能根据本地文件的时间戳以编程方式显示文本?
理想情况下,用户可以加载 mp3 和 vtt 文件,程序就可以运行了,但我不知道如何根据时间解析和自动化文本,甚至不知道如何在没有时间戳的情况下显示文本。
如有任何帮助,我们将不胜感激。
import Foundation
import RegexBuilder
let testString = """
WEBVTT
00:00:00.000 --> 00:00:04.560
Did you know that up to 80 to 90 percent
00:00:04.560 --> 00:00:09.080
of those making a decision to Code will hit a wall and give up?
00:00:09.080 --> 00:00:14.920
What? Yes, it's true. Did you know that most people give up within the first year?
00:00:14.920 --> 00:00:19.400
Some extra dialog would go here
00:00:19.400 --> 00:00:23.360
also additional dialog would also go here
"""
let patternTest = Regex {
/^/
Capture {
Regex {
Repeat(count: 2) {
One(.digit)
}
":"
Repeat(count: 2) {
One(.digit)
}
":"
Repeat(count: 2) {
One(.digit)
}
One(.anyOf(".,"))
Repeat(count: 3) {
One(.digit)
}
}
}
One(.whitespace)
"-->"
One(.whitespace)
Capture {
Regex {
Repeat(count: 2) {
One(.digit)
}
":"
Repeat(count: 2) {
One(.digit)
}
":"
Repeat(count: 2) {
One(.digit)
}
One(.anyOf(".,"))
Repeat(count: 3) {
One(.digit)
}
}
}
"\u{A}"
Capture {
Regex {
ZeroOrMore {
/./
}
ZeroOrMore {
Regex {
Optionally {
"\u{D}"
}
"\u{A}"
NegativeLookahead {
Regex {
Optionally {
"\u{D}"
}
"\u{A}"
}
}
ZeroOrMore {
/./
}
}
}
}
}
}
.anchorsMatchLineEndings()
let matches = testString.matches(of: patternTest)
// Creating an array of string type
// Using for loop to iterate through each element of the array
print("")
print("")
print("Array of Text elements are:")
for match14 in matches {
let (notSureWhatGoesHere) = match14.output
print(match14.output.3)
}
这将使用 RegexBuilder 代码循环遍历 Swift 5.7 中 WebVTT 格式文本中文本的所有匹配项。
如果您希望循环遍历第一个时间戳的所有匹配项,请将“print(match14.output.3”更改为“print(match14.output.1”)。如果您需要所有结束时间戳,请将其更改为“print(match14 .输出.2)".
这是我在 Swift Playground 中工作的东西,并且在 iOS 16.4.1 和 macOS 13.3.1 上为我工作,没有出现任何问题
在弄清楚这一点时,我不确定其中一个“let”的含义是什么,所以使用“notSureWhatGoesHere”,再次学习......
这不是我正在寻找的完整解决方案,但这是朝着正确方向迈出的一大步,希望这对其他人也有帮助。