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

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