本文主要是介绍Android:本地音乐文件写入专辑图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
网上搜索这个 Android写入专辑图的资料少之又少,都是读取的,这里我找到了一个方法,然后自己做了个写入专辑图的小工具,有需要的童鞋可以参考一下。
先上效果图:
依赖第三方库:jaudiotagger(java)、Okhttp
demo语言:Kotlin
不会kotlin的小伙伴别慌,我也是边学kotlin先写的这个demo,看过kotlin基础语法的小伙伴应该还是比较好理解的。
核心写入代码:
//path:本地音乐文件路径;picFile:本地图片文件(网络图片的话我这边的做法是保存到本地再用路径new一个文件)
fun writeTag(path: String?, picFile: File?) {val mp3File = MP3File(path)if (mp3File.hasID3v2Tag()) {mp3File.run {val artWork = ArtworkFactory.createArtworkFromFile(picFile)iD3v2Tag.setField(artWork)save()}}}
三步:
- 首先我们要获取本地所有音乐文件
- 然后点击某个item为它搜索专辑图(这里用网易云音乐搜索API)
- 最后就是写入
存储权限什么的这里就不写了,可以参考demo或者自己经验写。下面是获取本地音乐文件列表:
/*** 得到媒体的音乐文件列表*/private fun getMusicList(): MutableList<SongBean> {val list: MutableList<SongBean> = ArrayList()val cursor: Cursor? = this.contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Audio.AudioColumns.IS_MUSIC)if (cursor != null) {var song: SongBeanwhile (cursor.moveToNext()) {var singer = ""var name = ""val path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))val split = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)).split("-")val size = split.sizewhen {size == 1 -> {name = split[0]}size == 2 -> {singer = split[0]name = split[1]}size > 2 -> {name = split.last()for (i in 0 until size-1){singer += " "+split[i]}}}song = SongBean(name.replace(".mp3", "").trim(), singer.trim(), path)list.add(song)}cursor.close()}list.reverse()return list}
这个SongBean是装音乐的实体,里面有歌名、歌手、路径(搜索歌曲的话这个路径用来存储图片链接):
class SongBean() :Parcelable{var name:String? = nullvar singer:String? = nullvar path:String? = nullconstructor(parcel: Parcel) : this() {name = parcel.readString()singer = parcel.readString()path = parcel.readString()}constructor(name: String?, singer: String?, path: String?) : this(){this.name = namethis.singer = singerthis.path = path}override fun writeToParcel(parcel: Parcel, flags: Int) {parcel.writeString(name)parcel.writeString(singer)parcel.writeString(path)}override fun describeContents(): Int {return 0}companion object CREATOR : Parcelable.Creator<SongBean> {override fun createFromParcel(parcel: Parcel): SongBean {return SongBean(parcel)}override fun newArray(size: Int): Array<SongBean?> {return arrayOfNulls(size)}}fun getArtBitmap(): Bitmap? {val myRetriever = MediaMetadataRetriever()try {myRetriever.setDataSource(path) // the URI of audio file} catch (e: Exception) {Log.e("error", "getArtBitmapError: $e")return null}val artwork = myRetriever.embeddedPicturereturn if (artwork != null) {BitmapFactory.decodeByteArray(artwork, 0, artwork.size)} else {null}}
}
这个SongBean里面实现了序列化,因为列表item点击之后我们要把这个item的数据传到下一个界面。然后最后面这个getArtBitmap方法是原生的用来获取歌曲自带专辑图的方法,待会列表展示的时候要用到。
初始化界面的时候,把歌曲列表给到RecyclerView,展示给用户:
item的布局很简单,就垂直并列的三个TextView加上最右边的ImageView:(三个TextView的id分别是tv1、tv2、tv3,图片id是img)
列表的适配器:
class MyListAdapter(private val data: MutableList<SongBean>) :RecyclerView.Adapter<MyListAdapter.MyViewHolder>() {private val TAG = "MyListAdapter"class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.adapter_item,parent, false))}override fun onBindViewHolder(holder: MyViewHolder, position: Int) {holder.itemView.apply {tv1.text = data[position].nametv2.text = data[position].singertv3.text = data[position].pathif(tv3.text.startsWith("http")){Log.i(TAG, "load_picture:${data[position].path}")img.visibility = View.VISIBLEimg.load(data[position].path){crossfade(true)}}else{val artBitmap = data[position].getArtBitmap()if(artBitmap != null){img.visibility = View.VISIBLEimg.setImageBitmap(artBitmap)}else{img.visibility = View.GONE}}setOnClickListener{listener?.setOnItemClickListener(data[position],position)}}}override fun getItemCount(): Int = data.sizeprivate var listener:OnListener? = nullfun setListener(listener:OnListener){this.listener = listener}interface OnListener{fun setOnItemClickListener(bean: SongBean,position: Int)}fun setNewData(newData: List<SongBean>){data.clear()data.addAll(newData)notifyDataSetChanged()}
}
给recyclerView赋值:
allList = getMusicList()recycler.adapter = adapterrecycler.layoutManager = LinearLayoutManager(this)adapter.setListener(object : MyListAdapter.OnListener {override fun setOnItemClickListener(bean: SongBean,position:Int) {this@ListActivity.position = positionval intent = Intent(this@ListActivity, MatchActivity::class.java)intent.putExtra("data", bean)startActivityForResult(intent,1000)}})adapter.setNewData(allList)
这里用startActivityForResult是因为待会在下一个界面如果写入专辑图成功的话,返回出来需要更新这个item的右边图片,所以这个页面我把点击的position保存到全局变量里面。
到达下一个界面了之后,就搜索歌手+歌名,用的oktttp。
网易云歌曲搜索api:
http://music.163.com/api/search/pc?csrf_token=hlpretag=&hlposttag=&s=关键词&type=1&offset=页数从0开始&total=true&limit=每页数量
fun search(name: String?, singer: String?) {btn_search.isEnabled = falsebtn_search.text = "搜索中……"if (TextUtils.isEmpty(name) && TextUtils.isEmpty(singer)) {Toast.makeText(this, "请输入歌曲信息", Toast.LENGTH_SHORT).show()return}val word = singer?.trim() + name?.trim()val url = "http://music.163.com/api/search/pc?csrf_token=hlpretag=&hlposttag=&s=$word&type=1&offset=0&total=true&limit=20"Log.i(TAG, "search: $url")val okHttpClient = OkHttpClient()val request: Request = Request.Builder().url(url).header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)").build()val call = okHttpClient.newCall(request)call.enqueue(object : Callback {override fun onFailure(call: Call, e: IOException) {//失败处理btn_search.isEnabled = truebtn_search.text = "搜索"Toast.makeText(applicationContext, "请求失败", Toast.LENGTH_SHORT).show()}override fun onResponse(call: Call, response: Response) {val jsonObject = JSONObject(response.body()!!.string())runOnUiThread {btn_search.isEnabled = truebtn_search.text = "搜索"val code: Int = jsonObject.getInt("code")if (code == 200) {val jsonArray = jsonObject.getJSONObject("result").getJSONArray("songs")val list = ArrayList<SongBean>()for (i in 0 until jsonArray.length()) {val item = jsonArray.get(i) as JSONObjectval singerArr = item.getJSONArray("artists")var singerStr = ""for (j in 0 until singerArr.length()){val singerObj = singerArr.get(j) as JSONObjectsingerStr += singerObj.get("name")singerStr += " "}list.add(SongBean(item.getString("name"),singerStr,item.getJSONObject("album").getString("picUrl")))}adapter.setNewData(list)if (adapter.itemCount == 0) {Toast.makeText(applicationContext, "什么都没有搜到", Toast.LENGTH_SHORT).show()}} else {Toast.makeText(applicationContext, "服务器数据错误", Toast.LENGTH_SHORT).show()}}}})}
设置列表的点击事件,确定写入弹框防误触:(这里我以为写入是个耗时操作,实际现象并不会耗时,秒写入)
adapter.setListener(object : MyListAdapter.OnListener {override fun setOnItemClickListener(bean: SongBean,position:Int) {val url = bean.pathval img = ImageView(applicationContext)img.load(url)alert("写入专辑图", "确定写入吗?") {negativeButton("下次一定") {}positiveButton("写入") {
// indeterminateProgressDialog("正在写入")val request = ImageRequest.Builder(this@MatchActivity).data(bean.path).target { drawable ->// Handle the result.val bitmapDrawable: BitmapDrawable = drawable as BitmapDrawableval bitmap: Bitmap = bitmapDrawable.bitmapval filePath = "${filesDir.absoluteFile}/temp.jpg";Log.i(TAG, "filePath: $filePath")val file = bitmapToFile(filePath,bitmap, 80)Log.i(TAG, "BitmapFilePath: ${file?.absoluteFile}")writeTag(path, File(filePath))}.build()val disposable = imageLoader.enqueue(request)}}.show()}})
这里用到的保存bitmap到本地,还有写入专辑图的方法
/*** bitmap保存为file*/@Throws(IOException::class)fun bitmapToFile(filePath: String,bitmap: Bitmap?, quality: Int) : File? {if (bitmap != null) {val file = File(filePath.substring(0,filePath.lastIndexOf(File.separator)))if (!file.exists()) {file.mkdirs()}val bos = BufferedOutputStream(FileOutputStream(filePath))bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos)bos.flush()bos.close()return file}return null}/*** 写入专辑图*/
fun writeTag(path: String?, picFile: File?) {val mp3File = MP3File(path)if (mp3File.hasID3v2Tag()) {mp3File.run {val artWork = ArtworkFactory.createArtworkFromFile(picFile)iD3v2Tag.setField(artWork)save()Toast.makeText(applicationContext, "写入完成", Toast.LENGTH_SHORT).show()setResult(1001)}}else{Toast.makeText(applicationContext, "此歌曲没有ID3v2Tag", Toast.LENGTH_SHORT).show()}}
写入专辑图我也是百度搜的方法,这里判断了本地音乐文件需要有ID3v2Tag才能写入,我测试写了ID3v1Tag.setField确实没有作用,我自己的本地歌曲确实有那么几首是这样的,如果有知道的大佬可以指点一二。不过大部分歌曲都是有这个id3v2tag的。
至此所有核心方法都已给出。具体代码可以参照demo,代码我已上传GitHub:https://github.com/xaEHu/Mp3TagTool
这篇关于Android:本地音乐文件写入专辑图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!