《go语言编程》音乐库代码

zistxym · · 2929 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

F:\golang

├─bin
├─pkg
│ 
│                  
└─src
    │  mplayer.go
    │  
    └─mplayer
        ├─library
        │      manager.go
        │      manager_test.go
        │      
        └─mp
                mp3.go

                play.go

GOPATH设为f:\golang

书中有一些错误的地方,改一下

myplay.go

======

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
    "mplayer/library"
    "mplayer/mp"
)
var lib *library.MusicManager
var id int = 1
var ctrl, signal chan int
func handleLibCommands(tokens []string) {
    if len(tokens) < 2 {
        fmt.Println(` 
      Enter following commands to control the player: 
      lib list -- View the existing music lib 
      lib add <name><artist><source><type> -- Add a music to the music lib 
      lib remove <name> -- Remove the specified music from the lib 
      `)
        return
    }
    switch tokens[1] {
    case "list":
        for i := 0; i < lib.Len(); i++ {
            e, _ := lib.Get(i)
            fmt.Println(i+1, ":", e.Name, e.Artist, e.Source, e.Type)
        }
    case "add":
        {
            if len(tokens) == 6 {
                id++
                lib.Add(&library.MusicEntry{strconv.Itoa(id),
                    tokens[2], tokens[3], tokens[4], tokens[5]})
            } else {
                fmt.Println("USAGE: lib add <name><artist><source><type>")
            }
        }
    case "remove":
        if len(tokens) == 3 {
            index, _ := strconv.Atoi(tokens[2])
            lib.Remove(index)
        } else {
            fmt.Println("USAGE: lib remove <name>")
        }
    default:
        fmt.Println("Unrecognized lib command:", tokens[1])
    }
}
func handlePlayCommand(tokens []string) {
    if len(tokens) != 2 {
        fmt.Println("USAGE: play <name>")
        return
    }
    e := lib.Find(tokens[1])
    if e == nil {
        fmt.Println("The music", tokens[1], "does not exist.")
        return
    }
    mp.Play(e.Source, e.Type)
}
func main() {
    lib = library.NewMusicManager()
    fmt.Println(` 
      Enter following commands to control the player: 
      lib list -- View the existing music lib 
      lib add <name><artist><source><type> -- Add a music to the music lib 
      lib remove <name> -- Remove the specified music from the lib 
      play <name> -- Play the specified music 
       q   -- quit 
 `)
    r := bufio.NewReader(os.Stdin)
    for {
        fmt.Print("Enter command-> ")
        rawLine, _, _ := r.ReadLine()
        line := string(rawLine)
        if line == "q" || line == "e" {
            break
        }
        tokens := strings.Split(line, " ")
        if tokens[0] == "lib" {
            handleLibCommands(tokens)
        } else if tokens[0] == "play" {
            handlePlayCommand(tokens)
        } else {
            fmt.Println("Unrecognized command:", tokens[0])
        }
    }
}

play.go

======

package mp

import "fmt"
type Player interface {
    Play(source string)
}
func Play(source, mtype string) {
    var p Player
    switch mtype {
    case "MP3":
        p = &MP3Player{}
    case "WAV":
        //p = &WAVPlayer{}
    default:
        fmt.Println("Unsupported music type", mtype)
        return
    }
    p.Play(source)
}

mp3.go

========

package mp

import (
    "fmt"
    "time"
)
type MP3Player struct {
    stat     int
    progress int
}
func (p *MP3Player) Play(source string) {
    fmt.Println("Playing MP3 music", source)
    p.progress = 0
    for p.progress < 100 {
        time.Sleep(100 * time.Millisecond) //  假装正在播放
        fmt.Print(".")
        p.progress += 10
    }
    fmt.Println("\nFinished playing", source)
}

manager.go

=============

package library

import "errors"
type MusicEntry struct {
    Id     string
    Name   string
    Artist string
    Source string
    Type   string
}
type MusicManager struct {
    musics []MusicEntry
}
func NewMusicManager() *MusicManager {
    return &MusicManager{make([]MusicEntry, 0)}
}
func (m *MusicManager) Len() int {
    return len(m.musics)
}
func (m *MusicManager) Get(index int) (music *MusicEntry, err error) {
    if index < 0 || index >= len(m.musics) {
        return nil, errors.New("Index out of range.")
    }
    return &m.musics[index], nil
}
func (m *MusicManager) Find(name string) *MusicEntry {
    if len(m.musics) == 0 {
        return nil
    }
    for _, m := range m.musics {
        if m.Name == name {
            return &m
        }
    }
    return nil
}
func (m *MusicManager) Add(music *MusicEntry) {
    m.musics = append(m.musics, *music)
}
func (m *MusicManager) Remove(index int) *MusicEntry {
    if index < 0 || index >= len(m.musics) {
        return nil
    }
    removedMusic := &m.musics[index]
    // 从数组切片中删除元素
    if index < len(m.musics)-1 { // 中间元素
        m.musics = append(m.musics[:index-1], m.musics[index+1:]...)
    } else if index == 0 { // 删除仅有的一个元素
        m.musics = make([]MusicEntry, 0)
    } else { //  删除的是最后一个元素
        m.musics = m.musics[:index-1]
    }
    return removedMusic
}
manager_test.go

=============

package library

import (
    "testing"
)
func TestOps(t *testing.T) {
    mm := NewMusicManager()
    if mm == nil {
        t.Error("NewMusicManager failed.")
    }
    if mm.Len() != 0 {
        t.Error("NewMusicManager failed, not empty.")
    }
    m0 := &MusicEntry{
        "1", "My Heart Will Go On", "Celion Dion",
        "http://qbox.me/24501234", "MP3"}
    mm.Add(m0)
    if mm.Len() != 1 {
        t.Error("MusicManager.Add() failed.")
    }
    m := mm.Find(m0.Name)
    if m == nil {
        t.Error("MusicManager.Find() failed.")
    }
    if m.Id != m0.Id || m.Artist != m0.Artist ||
        m.Name != m0.Name ||
        m.Source != m0.Source || m.Type != m0.Type {
        t.Error("MusicManager.Find() failed. Found item mismatch.")
    }
    m, err := mm.Get(0)
    if m == nil {
        t.Error("MusicManager.Get() failed.", err)
    }
    m = mm.Remove(0)
    if m == nil || mm.Len() != 0 {
        t.Error("MusicManager.Remove() failed.", err)
    }
}


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:zistxym

查看原文:《go语言编程》音乐库代码

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:1006366459

2929 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传