unity开发简易的本地音乐播放器
由于项目需要,做了个简单的本地音乐播放器demo,记录一下,万一以后就用到了。
UI不方便贴图,只贴关键功能的代码。
功能1:从本地选择音频文件。
这部分代码是在网上搜索到的,由于不知道原创是哪位前辈(因为所有人都标着原创),所以就不贴出处了,代码看起来感觉很懵,但是其实可以直接复制粘贴使用,只限pc端。
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;public class LocalDialog {//链接指定系统函数 打开文件对话框[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);public static bool GetOFN([In, Out] OpenFileName ofn){return GetOpenFileName(ofn);}//链接指定系统函数 另存为对话框[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern bool GetSaveFileName([In, Out] OpenFileName ofn);public static bool GetSFN([In, Out] OpenFileName ofn){return GetSaveFileName(ofn);}
}
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{public int structSize = 0;public IntPtr dlgOwner = IntPtr.Zero;public IntPtr instance = IntPtr.Zero;public String filter = null;public String customFilter = null;public int maxCustFilter = 0;public int filterIndex = 0;public String file = null;public int maxFile = 0;public String fileTitle = null;public int maxFileTitle = 0;public String initialDir = null;public String title = null;public int flags = 0;public short fileOffset = 0;public short fileExtension = 0;public String defExt = null;public IntPtr custData = IntPtr.Zero;public IntPtr hook = IntPtr.Zero;public String templateName = null;public IntPtr reservedPtr = IntPtr.Zero;public int reservedInt = 0;public int flagsEx = 0;
}
使用方式如下,LocalDialog.GetOFN(openFileName) ==true 表示选择了文件,在这里面进行操作,其中allsonglist存储了所有已经添加的文件路径,所以先判断下是否已添加。updatePlayPrefab为更新本地存储的,show为ui显示方法。
public void checkSong(){OpenFileName openFileName = new OpenFileName();openFileName.structSize = Marshal.SizeOf(openFileName);openFileName.filter = "mp3文件(*.mp3)\0*.mp3";openFileName.file = new string(new char[256]);openFileName.maxFile = openFileName.file.Length;openFileName.fileTitle = new string(new char[64]);openFileName.maxFileTitle = openFileName.fileTitle.Length;openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默认路径openFileName.title = "窗口标题";openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;if (LocalDialog.GetOFN(openFileName)){if(allSongList.Contains(openFileName.file)){Tip.show("歌曲已存在,无需重复添加");}else{allSongList.Add(openFileName.file);updatePlayPrefab();show();}//Debug.Log(openFileName.fileTitle);}}
功能2:本地歌曲路径储存以及更新
即歌曲列表显示用户已经选择过的音乐,原理是用特殊字符串连接各个文件路径,然后使用PlayerPrefs存储,打开应用的时候解析数据,显示列表。下面为解析,字符串的简单处理
const string songData = "SongListData";string[] sign =new string[] {"_|bzy|_" } ;//地址之间分隔符public void OnEnable(){allSongList = new List<string>();//if (PlayerPrefs.HasKey(songData)){string value = PlayerPrefs.GetString(songData);Debug.Log(value);string[] strArr = value.Split(sign,StringSplitOptions.None);for (int i = 0; i < strArr.Length; i++){if(!string.IsNullOrEmpty( strArr[i])){allSongList.Add(strArr[i]);Debug.Log(allSongList[i]);}}}else{PlayerPrefs.SetString(songData,"");}show();}
下面是存储更新,每次选择音乐以及删除的时候都要更新
string playPrefabValue;void updatePlayPrefab(){playPrefabValue = string.Empty;string mid = string.Empty;for (int i = 0; i < allSongList.Count; i++){playPrefabValue = string.Format("{0}{1}{2}", i == 0 ? "" : playPrefabValue,i == 0 ? "" : sign[0], allSongList[i]);}PlayerPrefs.SetString(songData,playPrefabValue);}
功能3:播放,上一首,下一首,删除
播放需要用到audiosource组件,给组件的audioclip赋值,然后调用play播放,audioclip的获取需要用到www。为了避免多次下载audioclip,应该将下载过的audioclip存储起来,这里使用了字典,key为文件路径。clip.length为时长。
int currentIndex;//当前播放的索引string currentSongPath;//当前播放的路径Dictionary<string,AudioClip> allClipList;//key path , value audioclippublic void playMusic(string path){CancelInvoke("playNext");if (allClipList == null) allClipList = new Dictionary<string, AudioClip>();if(string.IsNullOrEmpty(path)){currentIndex = 0;currentSongPath = allSongList[currentIndex];currentSongNameTxt.text = Path.GetFileName(currentSongPath);}else{currentIndex = allSongList.IndexOf(path);currentSongPath = path;currentSongNameTxt.text = Path.GetFileName(path);}if (allClipList.ContainsKey(currentSongPath))//clip已下载{audio.clip = allClipList[currentSongPath];audio.Play();Invoke("playNext", clip.length);}else{StartCoroutine("DownLoad");}//Invoke("playNext",5);}IEnumerator DownLoad(){Debug.Log("下载。。。。");WWW www = new WWW("file://" + currentSongPath);yield return www;if (string.IsNullOrEmpty(www.error)){clip = www.GetAudioClip();allClipList.Add(currentSongPath,clip);audio.clip = clip;audio.Play();Invoke("playNext",clip.length);}else{Debug.LogError(www.error);}}//下一曲public void playNext(){currentIndex = (currentIndex + 1) % allSongList.Count;playMusic(allSongList[currentIndex]);}//上一曲public void playLast(){currentIndex = currentIndex == 0 ? allSongList.Count - 1 : (currentIndex - 1) % allSongList.Count;playMusic(allSongList[currentIndex]);}
删除
public void deleteSong(string path){if (!allSongList.Contains(path)){Debug.Log("删除失败,不包含此歌曲");}else{if (allClipList.ContainsKey(path)) allClipList.Remove(path);allSongList.Remove(path);updatePlayPrefab();show();}}
播放模式什么的也好说,不需要也就没实现。记录结束
unity开发简易的本地音乐播放器相关推荐
- 简易的本地音乐播放器 适用于Java初学者
简易的本地音乐播放器 适用于Java初学者 我知道肯定会有人说都1202年了怎么还有人在用AudioClip,没有别的原因,因为我也刚学Java,刚好看到一个这样的教程就刚好写了一个这样的播放器. 我 ...
- python开发音乐播放器教程_python开发简易版在线音乐播放器示例代码
在线音乐播放器,使用python的Tkinter库做了一个界面,感觉这个库使用起来还是挺方便的,音乐的数据来自网易云音乐的一个接口,通过urllib.urlopen模块打开网址,使用Json模块进行数 ...
- 我的音乐(Musicoco)- 本地音乐播放器开发总结
开源一个功能相对齐全的本地音乐播放器 简述 从五月末就开始利用空余时间开发这款 app ,不知不觉三个月过去了. App 名称:我的音乐,我给取了个别名:Musicoco. Android 手机本地音 ...
- 基于 Qt5 ( C++ ) 开发的一个小巧精美的本地音乐播放器
LightMusicPlayer --南京大学2019秋季学期 "高级程序设计" 课程设计三 基于Qt5开发的一个小巧精美的本地音乐播放器 代码注释详细,适合作为一个用于入门的Qt ...
- 炫 音乐可视化 html5 在线,HTML5打造的炫酷本地音乐播放器-喵喵Player
将之前捣腾的音乐频谱效果加上一个播放列表就成了现在的喵喵播放器(Meow meow Player,额知道这名字很二很装萌~),全HTML5打造的网页程序,可本地运行也可以挂服务器上用. 在线Demo及 ...
- python 本地音乐播放器制作过程
制作这个播放器的目的是为了将下载下来的mp3文件进行随机或是顺序的播放.选择需要播放的音乐的路径,选择播放方式,经过测试可以完美的播放本地音乐. [阅读全文] 在开始之前介绍一个免费下载mp3音乐的网 ...
- Android端本地音乐播放器(一)---前言
前言: 2018时的记录:大概一周多以前(现在是2018.11.26 15:24)android平台开发的课程结束了,要写大作业,最后决定写这个音乐播放器,因为老师在课堂上讲的例子也是这个,前面的 ...
- 用JavaScript实现简易的网页音乐播放器
用JavaScript实现简易的网页音乐播放器 最近疫情在家,利用这段时间开始自学HTML等内容,目前在写自己的个人主页,想用音乐来给自己的主页增添点特色. 一开始单纯用audio标签添加音乐,带上a ...
- 基于Phonon的本地音乐播放器
基于Phonon的本地音乐播放器 之前逛博客的时候偶然看到一个音乐播放器的小项目,于是这两天也动手写了一个基于Phonon的本地音乐播放器.使用版本为Qt4.7.3. 目前的功能不多,界面也比较丑.后 ...
最新文章
- 力扣(LeetCode)刷题,简单题(第11期)
- 四川音乐学录音艺术与计算机音乐,艺考中作曲专业和录音专业有什么不同呢?...
- table control中用帮助(F4)实现自动填充另一字段
- C#:绘制Winform窗体
- 外贸EDM邮件营销效率低的原因分析
- Gradle里Copy任务(task)的使用
- 12、oracle数据库下的存储过程和函数
- C++数组指针不能自增1/自减1
- WebAssembly 介绍
- Java使用百度翻译api
- 《商务与经济统计》学习笔记(三)
- onenote2019导入_将OneNote 2010笔记本导入Evernote
- 上位机和下位机有什么区别和关系?常用上位机软件开发工具介绍
- 海量数据(面向面试)
- 微信小程序中的转发功能
- Vue 做调查问卷简单实例
- import math java_java 中 Math类
- android rtmp推流,使用MediaCodec和RTMP做直播推流
- pycurl和urllib2的比较
- 计算机专业的学生答辩稿,计算机专业毕业论文答辩自述稿范文
热门文章
- html5地图连线原理,基于html5技术绘制上海地铁图 – 双车道路况信息
- arduino / VScode+platformIO搭建esp32/esp8266编译环境(一篇足矣)
- 黑客入侵“在线影院”全过程1
- php111个人备忘录通讯录系统
- 【Python】端口号脚本,避免端口号冲突
- 商业数据分析的四个层次
- c语言负数左移右移_C语言中关于循环左移和循环右移
- 安徽大学入学计算机考试模拟试题,安徽大学计算机图形学期末考试试卷
- 计算机硬件行业上下游,浅析GIS行业上下游产业链
- sqlserver重新自动生成编号