golang解析和生成Apple m3u8播放列表插件库go-m3u8的使用

Golang解析和生成Apple m3u8播放列表插件库go-m3u8的使用

介绍

go-m3u8是一个用于生成和解析m3u8播放列表的Golang包,它实现了Apple发布的HTTP Live Streaming (HLS) Internet Draft第20版。主要功能包括:

  • 从任何文件、io.Reader或字符串解析m3u8播放列表到对象模型
  • 通过String()方法将播放列表写入字符串
  • 自动处理主播放列表和媒体播放列表的区别
  • 可选自动生成CODEC属性中使用的音频/视频编解码器字符串

安装

go get github.com/etherlabsio/go-m3u8

创建播放列表

创建主播放列表

import (
    "github.com/etherlabsio/go-m3u8/m3u8"
    "github.com/AlekSi/pointer"
)

// 创建新播放列表
playlist := m3u8.NewPlaylist()

// 创建播放列表项
item := &m3u8.PlaylistItem{
    Width:      pointer.ToInt(1920),
    Height:     pointer.ToInt(1080),
    Profile:    pointer.ToString("high"),
    Level:      pointer.ToString("4.1"),
    AudioCodec: pointer.ToString("aac-lc"),
    Bandwidth:  540,
    URI:        "test.url",
}
playlist.AppendItem(item)

添加备用音频、字幕等

item := &m3u8.MediaItem{
    Type:          "AUDIO",
    GroupID:       "audio-lo",
    Name:          "Francais",
    Language:      pointer.ToString("fre"),
    AssocLanguage: pointer.ToString("spoken"),
    AutoSelect:    pointer.ToBool(true),
    Default:       pointer.ToBool(false),
    Forced:        pointer.ToBool(true),
    URI:           pointer.ToString("frelo/prog_index.m3u8"),
}
playlist.AppendItem(item)

创建标准播放列表

playlist := &m3u8.Playlist{
    Target:   12,
    Sequence: 1,
    Version:  pointer.ToInt(1),
    Cache:    pointer.ToBool(false),
    Items: []m3u8.Item{
        &m3u8.SegmentItem{
            Duration: 11,
            Segment:  "test.ts",
        },
    },
}

手动指定编解码器

item := &m3u8.PlaylistItem{
    Width:     pointer.ToInt(1920),
    Height:    pointer.ToInt(1080),
    Codecs:    pointer.ToString("avc1.66.30,mp4a.40.2"),
    Bandwidth: 540,
    URI:       "test.url",
}

解析播放列表

从文件解析

playlist, err := m3u8.ReadFile("path/to/file")

从字符串解析

playlist, err := m3u8.ReadString(string)

从io.Reader解析

playlist, err := m3u8.Read(reader)

访问播放列表项

playlist.Items[0]  // 第一个播放列表项
playlist.Items[1]  // 第二个播放列表项

编解码器选项

  • 音频编解码器(audio_codec)可选值: aac-lc, he-aac, mp3
  • H.264 Profile可选值: baseline, main, high
  • H.264 Level可选值: 3.0, 3.1, 4.0, 4.1

注意并非所有Level和Profile都可以组合使用,目前库中没有实现验证,详情请参考H.264文档。

完整示例

package main

import (
	"fmt"
	"github.com/AlekSi/pointer"
	"github.com/etherlabsio/go-m3u8/m3u8"
)

func main() {
	// 创建主播放列表
	playlist := m3u8.NewPlaylist()

	// 添加视频流
	videoItem := &m3u8.PlaylistItem{
		Width:      pointer.ToInt(1920),
		Height:     pointer.ToInt(1080),
		Profile:    pointer.ToString("high"),
		Level:      pointer.ToString("4.1"),
		AudioCodec: pointer.ToString("aac-lc"),
		Bandwidth:  5400000,
		URI:        "video_1080p.m3u8",
	}
	playlist.AppendItem(videoItem)

	// 添加备用音频
	audioItem := &m3u8.MediaItem{
		Type:          "AUDIO",
		GroupID:       "audio-lo",
		Name:          "English",
		Language:      pointer.ToString("eng"),
		AutoSelect:    pointer.ToBool(true),
		Default:       pointer.ToBool(true),
		URI:           pointer.ToString("audio_eng.m3u8"),
	}
	playlist.AppendItem(audioItem)

	// 生成播放列表字符串
	fmt.Println(playlist.String())
}

这个示例展示了如何创建一个包含1080p视频流和英语音频的主播放列表。你可以根据需要添加更多视频流或音频轨道。


更多关于golang解析和生成Apple m3u8播放列表插件库go-m3u8的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang解析和生成Apple m3u8播放列表插件库go-m3u8的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


go-m3u8 库使用指南

go-m3u8 是一个用于解析和生成 Apple HLS (HTTP Live Streaming) m3u8 播放列表的 Go 语言库。下面我将详细介绍如何使用这个库。

安装

go get github.com/quangngotan95/go-m3u8/m3u8

基本概念

m3u8 是 HLS 协议使用的播放列表格式,主要有两种类型:

  • 主播放列表 (Master Playlist)
  • 媒体播放列表 (Media Playlist)

解析 m3u8 文件

解析主播放列表

package main

import (
	"fmt"
	"os"

	"github.com/quangngotan95/go-m3u8/m3u8"
)

func main() {
	// 读取m3u8文件内容
	data, err := os.ReadFile("master.m3u8")
	if err != nil {
		panic(err)
	}

	// 解析播放列表
	playlist, err := m3u8.Parse(string(data))
	if err != nil {
		panic(err)
	}

	// 判断是否是主播放列表
	if playlist.IsMaster() {
		master := playlist.(*m3u8.MasterPlaylist)
		// 遍历所有变体流
		for _, variant := range master.Variants {
			fmt.Printf("Bandwidth: %d, Resolution: %s, URI: %s\n",
				variant.Bandwidth,
				variant.Resolution,
				variant.URI)
		}
	}
}

解析媒体播放列表

func parseMediaPlaylist() {
	data, err := os.ReadFile("media.m3u8")
	if err != nil {
		panic(err)
	}

	playlist, err := m3u8.Parse(string(data))
	if err != nil {
		panic(err)
	}

	if !playlist.IsMaster() {
		media := playlist.(*m3u8.MediaPlaylist)
		fmt.Printf("Target Duration: %f\n", media.TargetDuration)
		fmt.Printf("Sequence: %d\n", media.Sequence)
		fmt.Printf("Segments Count: %d\n", len(media.Segments))
		
		for _, seg := range media.Segments {
			fmt.Printf("Duration: %f, URI: %s\n", seg.Duration, seg.URI)
		}
	}
}

生成 m3u8 文件

创建主播放列表

func createMasterPlaylist() {
	playlist := m3u8.NewMasterPlaylist()
	
	// 添加变体流
	playlist.Append(
		"video-800k.m3u8",
		800000,
		"640x360",
		"avc1.42001e,mp4a.40.2")
	
	playlist.Append(
		"video-1200k.m3u8",
		1200000,
		"854x480",
		"avc1.42001f,mp4a.40.2")
	
	// 设置独立属性
	playlist.IndependentSegments = true
	
	// 输出播放列表
	fmt.Println(playlist.String())
}

创建媒体播放列表

func createMediaPlaylist() {
	// 创建媒体播放列表,设置容量为10个片段
	playlist, err := m3u8.NewMediaPlaylist(10, 10)
	if err != nil {
		panic(err)
	}
	
	// 设置播放列表属性
	playlist.TargetDuration = 6
	playlist.Sequence = 1
	playlist.MediaType = m3u8.VOD // 点播类型
	
	// 添加媒体片段
	playlist.Append("segment1.ts", 5.0, "")
	playlist.Append("segment2.ts", 5.0, "")
	playlist.Append("segment3.ts", 5.0, "")
	
	// 关闭播放列表(对于VOD很重要)
	playlist.Close()
	
	// 输出播放列表
	fmt.Println(playlist.String())
}

高级功能

添加自定义标签

func addCustomTags() {
	playlist := m3u8.NewMasterPlaylist()
	
	// 添加EXT-X-VERSION标签
	playlist.SetVersion(3)
	
	// 添加自定义注释
	playlist.SetComments([]string{"Generated by go-m3u8"})
	
	// 添加其他自定义标签
	playlist.SetCustomTag(m3u8.CustomTag{
		Name:  "EXT-X-MY-TAG",
		Value: "custom-value",
	})
	
	fmt.Println(playlist.String())
}

处理加密片段

func handleEncryptedSegments() {
	playlist, _ := m3u8.NewMediaPlaylist(5, 5)
	
	// 添加加密信息
	key := &m3u8.Key{
		Method:            "AES-128",
		URI:               "https://example.com/key.bin",
		IV:                "0x1234567890ABCDEF1234567890ABCDEF",
		KeyFormat:         "identity",
		KeyFormatVersions: "1",
	}
	
	playlist.Key = key
	
	// 添加加密片段
	playlist.Append("encrypted1.ts", 5.0, "")
	playlist.Append("encrypted2.ts", 5.0, "")
	
	fmt.Println(playlist.String())
}

注意事项

  1. 对于媒体播放列表,如果是VOD类型,必须调用Close()方法
  2. 创建媒体播放列表时需要指定初始容量和最大容量
  3. 解析时注意检查播放列表类型(IsMaster())
  4. 处理大播放列表时注意内存使用

总结

go-m3u8 库提供了完整的 m3u8 播放列表解析和生成功能,支持 HLS 协议的各种特性。通过这个库,你可以轻松地在 Go 应用中集成 HLS 流媒体处理能力。

如果需要更高级的功能,可以查看库的源代码,它提供了丰富的 API 来处理各种 m3u8 特性和自定义需求。

回到顶部