go语言编程音乐库代码
go语言编程书上有一些代码有误和遗漏的地方,这里就行了修改与加如了一小段代码。
成都创新互联公司是工信部颁发资质IDC服务器商,为用户提供优质的简阳服务器托管服务
---开始,我也搜个百度,大多都是一样的,而且在remove代码块还是有些问题(不能是传name)。
好吧!!不多说了.下面展示所有的代码。
------------------------------------------------------------------------------------------------------
先贴入口文件.
mplayer.go
package main import ( "bufio" "fmt" "os" "strconv" "strings" "mplayer/library" //这里是目录结构哦,别放做了,src下的mplayer目录下的library目录 "mplayer/mp" //src下的mplayer目录下的mp目录 ) 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
manager.go //在mplayer目录下的library目录下
package library import ( "errors" "fmt" ) 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.") } //fmt.Println(m) 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) { fmt.Println("请重新选择删除的序号..") return nil } removedMusic := &m.musics[index-1] // 从数组切片中删除元素 if index < len(m.musics) { // 中间元素 m.musics = append(m.musics[:index-1], m.musics[index:]...) } else { // 删除的是最后一个元素 //fmt.Println("删除最后一个") m.musics = m.musics[:index-1] } return removedMusic }
mp3.go //mplayer 目录下的mp目录
package mp import ( "fmt" "time" ) type MP3Player struct { stat int progress int } type WAVPlayer 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) } func (p *WAVPlayer) Play(source string) { fmt.Println("Playing WAV music", source) p.progress = 0 for p.progress < 100 { time.Sleep(100 * time.Millisecond) // 假装正在播放 fmt.Print(".") p.progress += 10 } fmt.Println("\nFinished playing", source) }
play.go //mplayer目录下的mp目录下
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) }
-----------------------------------------------------------------------------------------------------
如上面有所遗漏或代码有误,请留言。欢迎勘误指正。
网站标题:go语言编程音乐库代码
链接分享:http://ybzwz.com/article/igohoo.html