Go语言面向对象编程——模拟音乐播放器

写在前面: 我是「虐猫人薛定谔i」,一个不满足于现状,有梦想,有追求的00后
\quad
本博客主要记录和分享自己毕生所学的知识,欢迎关注,第一时间获取更新。
\quad
不忘初心,方得始终。
\quad

❤❤❤❤❤❤❤❤❤❤

在这里插入图片描述

目录结构

在这里插入图片描述

设计思路

需要有一个音乐类,其属性如下所示

type MusicEntry struct {
	Id     string
	Name   string
	Artist string
	Source string
	Type   string
}

借助音乐类,实现一个音乐管理类,用来管理列表中的音乐,实现对列表中音乐的增加、删除、查找等操作

type MusicManager struct {
	musics []MusicEntry
}

其中core模块用来实现模拟音乐播放的功能,目前只实现了MP3和WAV文件,可以继续进行扩展
在mplayer中实现对播放器的控制,其中包括从键盘获取输入,并进行相应的处理操作

代码

mplayer.go

package main

import "bufio"
import "fmt"
import "os"
import "strconv"
import "strings"
import "SMP/m/src/library"
import "SMP/m/src/core"

var lib *library.MusicManager
var id = 1

func handleLibCommands(tokens []string) {
	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{Id: strconv.Itoa(id),
				Name: tokens[2], Artist: tokens[3], Source: tokens[4], Type: tokens[5]})
		} else {
			fmt.Println("USAGE: lib add <name><artist><source><type>")
		}
	case "remove":
		if len(tokens) == 3 {
			lib.RemoveByName(tokens[2])
		} 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")
	} else {
		core.Play(e.Source, e.Type)
	}
}

func main() {
	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
	`)
	lib = library.NewMusicManager()
	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])
		}
	}
}

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
	}
	removeMusic := &m.musics[index]
	if index < len(m.musics)-1 {
		m.musics = append(m.musics[:index], m.musics[index+1:]...)
	} else if index == 0 {
		m.musics = make([]MusicEntry, 0)
	} else {
		m.musics = m.musics[:index-1]
	}
	return removeMusic
}

func (m *MusicManager) RemoveByName(name string) *MusicEntry {
	index := -1
	for i, item := range m.musics {
		if item.Name == name {
			index = i
			break
		}
	}
	if index == -1 {
		return nil
	}
	return m.Remove(index)
}

play.go

package core

import "fmt"

type Player interface {
	Play(source string)
}

func Play(source, mtype string) {
	var p Player

	switch mtype {
	case "MP3":
		p = &PlayerMP3{}
	case "WAV":
		p = &PlayerWAV{}
	default:
		fmt.Println("Unsupported music type", mtype)
		return
	}
	p.Play(source)
}

mp3.go

package core

import "fmt"
import "time"

type PlayerMP3 struct {
	stat int
	progress int
}

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

wav.go

package core

import "time"
import "fmt"

type PlayerWAV struct {
	state int
	progress int
}


func (p *PlayerWAV)Play(source string) {
	fmt.Println("Playing WAV music", source)
	p.progress = 0
	for p.progress < 100 {
		time.Sleep(100 * time.Millisecond) // 假装正在播放
		fmt.Println(".")
		p.progress += 10
	}
	fmt.Println("\nFinished playing", source)
}

在这里插入图片描述

效果展示

自己准备了几条测试数据,下面让我们来看一下效果吧!希望代码没事。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

只是一个模拟的播放器,并没有实现真正的播放音乐。通过对音乐播放器的设计,可以帮助我们了解Go语言在面向对象编程中的设计方法。
在这里插入图片描述

蒟蒻写博客不易,加之本人水平有限,写作仓促,错误和不足之处在所难免,谨请读者和各位大佬们批评指正。
如需转载,请署名作者并附上原文链接,蒟蒻非常感激
名称:虐猫人薛定谔i
博客地址:https://blog.csdn.net/Deep___Learning

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章