- Home /
Android play mp3 file
Hi, i need your help so much, so i want to play a mp3 file into my android app, ok, i wrote the code using NAudio, and there's the problem, it works only on windows, on android i hear nothing, i mean the list of all music files i get but to play them i can't, pleaseee help mee. Oh, forgot to say that first it converts mp3 to wav(on line: audio.clip = NAudioPlayer.FromMp3Data (www.bytes);), i just tried someone's code, but it seems non-workable(just for PC) Full code is:
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using NAudio;
using NAudio.Wave;
public class MusicSelect : MonoBehaviour {
private string _curPath;
public List<string> _curMusicNames, _curMusicPaths;
public void GetCurFiles()
{
_curMusicNames.Clear ();
_curMusicPaths.Clear ();
_curPath = Directory.GetCurrentDirectory ();
Debug.Log ("Path:"+_curPath);
if (Application.platform != RuntimePlatform.Android)
return;
#if UNITY_ANDROID
using (AndroidJavaClass jcEnvironment = new AndroidJavaClass ("android.os.Environment"))
using (AndroidJavaObject joExDir = jcEnvironment.CallStatic<AndroidJavaObject> ("getExternalStorageDirectory")) {
_curPath = joExDir.Call<string> ("toString") + "/Music";
}
#endif
DirectoryInfo dir = new DirectoryInfo(_curPath);
FileInfo[] info = dir.GetFiles("*.mp3");
foreach (FileInfo f in info)
{
_curMusicNames.Add( f.Name );
_curMusicPaths.Add( f.FullName );
}
}
void OnGUI() {
if(_curMusicPaths.Count>0)
{
for(int i=0; i<_curMusicPaths.Count; i++)
{
if (GUI.Button(new Rect(0,i*170, Screen.width, 150),_curMusicPaths[i])){
Debug.Log ("Playing "+_curMusicNames[i]);
StartCoroutine (PlayThis("file://"+_curMusicPaths[i]));
}
}
}
}
IEnumerator PlayThis(string url)
{
WWW www = new WWW(url);
yield return www;
AudioSource audio = GetComponent<AudioSource>();
audio.clip = NAudioPlayer.FromMp3Data (www.bytes);
audio.Play();
}
}
Comment