极客时间 mp3提取

package main

import (
   "fmt"
   "io/ioutil"
   "net/http"
   "os"
   "regexp"
   "strings"
   "time"
)

var name ="AI技术内参"
var path string = "/Users/mac/www/book/其他书籍/"+name
func main() {
   fileInfos,err:=ioutil.ReadDir(path)
   if err!=nil{
      fmt.Println("ReadDir failed,error:%v\n",err)
      return
   }
   for _,info := range fileInfos{
      //1、一次性读取文件内容,还有一个 ReadAll的函数,也能读取
      fileName := path + "/"+info.Name()
      title := strings.Split(info.Name(),".")[0]

      data, err := ioutil.ReadFile(fileName)
      if err != nil {
         fmt.Println(err)
         return
      }

      context2 := string(data)

      exp3 := regexp.MustCompile(`https.*.mp3`)
      result3 := exp3.FindAllString(context2, -1)
      fmt.Println(title)
      if len(result3) > 0 {
         src := result3[0]
         fmt.Println(src)

         resp, err := http.Get(src)
         handError(err)

         defer resp.Body.Close()

         bytesContent, err := ioutil.ReadAll(resp.Body)
         os.Mkdir("/Users/mac/Desktop/"+name,0777)
         writeToFile("/Users/mac/Desktop/"+name+"/"+title+".mp3",string(bytesContent))
         time.Sleep(time.Second*1)
      }
   }
}

func writeToFile(path string,content string)  {

   //func WriteFile(filename string, data []byte, perm os.FileMode) error
   err := ioutil.WriteFile(path, []byte(content), 0666)
   fmt.Println("save file "+path)
   if err != nil {
      panic(err)
   }
}

func handError(err error)  {
   //fmt.Println(err)
   if err != nil{
      fmt.Println(err)
   }

}

  

posted @ 2021-09-08 20:01  brady-wang  阅读(188)  评论(0编辑  收藏  举报