n10v / id3v2

🎵 ID3 decoding and encoding library for Go
https://pkg.go.dev/github.com/bogem/id3v2/v2
MIT License
338 stars 52 forks source link

Need examples of setting attached pictures of a mp3 file #87

Closed xiebruce closed 11 months ago

xiebruce commented 11 months ago

I use the following code, no error but no effect too (go version go1.21.0 darwin/amd64).

package main

import (
    "fmt"
    "os"
    "path"
    "path/filepath"
    "runtime"
    "strings"

    "github.com/bogem/id3v2"
)

func main() {
    curDir := GetCurDir()
    mp3File := filepath.Join(curDir, "test.mp3")
    coverFile := filepath.Join(curDir, "cover.jpg")
    SetMp3Cover(mp3File, coverFile)
}

// SetMp3Cover Sets the attached picture of a mp3 file
func SetMp3Cover(mp3File string, coverFile string) {
    tag, err := id3v2.Open(mp3File, id3v2.Options{Parse: true})
    if err != nil {
        panic(err)
    }
    defer tag.Close()

    imageData, err := os.ReadFile(coverFile)
    if err != nil {
        panic(err)
    }

    tag.AddAttachedPicture(id3v2.PictureFrame{
        PictureType: id3v2.PTFrontCover,
        MimeType:    "image/jpeg",
        Description: "Front Cover",
        Picture:     imageData,
    })

    if err := tag.Save(); err != nil {
        panic(err)
    }
    fmt.Println("Set mp3 Cover successfully.")
}

// getSourceCodeDir Get the dir where the .go source code file located
func getSourceCodeDir() string {
    var abPath string
    _, filename, _, ok := runtime.Caller(0)
    if ok {
        abPath = path.Dir(filename)
    }
    return abPath
}

// GetCurDir Get the current dir
func GetCurDir() string {
    exePath, err := os.Executable()
    if err != nil {
        panic(err)
    }
    curDir := filepath.Dir(exePath)

    // if "go run .", the exePath will be as bellow
    // exePath: /var/folders/b8/m8lcy7wx235d02cwqsjphzjm0000gn/T/go-build1874405170/b001/exe/ncm2mp3

    // if "go run .", use the dir when .go source code file located
    // instead of the dir where the executable file located
    if strings.Contains(curDir, "go-build") {
        curDir = getSourceCodeDir()
    }
    return curDir
}

BTW, it seems I can set many Pictures? not only one?

xiebruce commented 11 months ago

Turns out that I didn't specify the encoding, now I solved the issue, I got the example from here

tag.AddAttachedPicture(id3v2.PictureFrame{
    Encoding:    id3v2.EncodingUTF8,
    MimeType:    "image/jpeg",
    PictureType: id3v2.PTFrontCover,
    Description: "Front cover",
    Picture:     metaData.AlbumPicB,
})