-
Notifications
You must be signed in to change notification settings - Fork 0
/
subtitle.go
61 lines (50 loc) · 1.13 KB
/
subtitle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"context"
"fmt"
"github.com/asticode/go-astisub"
"os"
"path/filepath"
"time"
)
func GenerateSubtitlesLocally(ctx context.Context, sentences []string, audios []string, outputPath string) (string, error) {
var subs astisub.Subtitles
startTime := 0 * time.Second
for i, sentence := range sentences {
duration := GetAudioDuration(audios[i])
endTime := startTime + duration
item := astisub.Item{
StartAt: startTime,
EndAt: endTime,
Lines: []astisub.Line{
{
Items: []astisub.LineItem{
{
Text: sentence,
},
},
},
},
}
subs.Items = append(subs.Items, &item)
startTime = endTime
}
fileUrl := fmt.Sprintf("%d.srt", time.Now().UnixNano())
videoPath := filepath.Join(outputPath, fileUrl)
// 创建文件所在的文件夹路径
err := os.MkdirAll(filepath.Dir(videoPath), os.ModePerm)
if err != nil {
return "", err
}
// 将字幕写入到本地文件
outputFile, err := os.Create(videoPath)
if err != nil {
return "", err
}
defer outputFile.Close()
err = subs.WriteToSRT(outputFile)
if err != nil {
return "", err
}
return videoPath, nil
}