【问题标题】:How to load mp3 files located on sdcard on android device?如何在 android 设备上加载位于 sdcard 上的 mp3 文件?
【发布时间】:2019-03-03 06:36:49
【问题描述】:

使用这个脚本,我可以从我的电脑上加载 mp3 文件:

public string path = C:\Users\PC\Desktop\myMusic.mp3

IEnumerator Start()
{

using (WWW www = new WWW(path))
{
yield return www;

source.clip = www.GetAudioClip();
source.Play();
}
}

但是,它不适用于 Android。 mp3 文件位于我的 SD 卡中的 MP3 文件夹中。我尝试了这些路径: “/storage/emulated/MP3/myMusic.mp3”; “/storage/sdcard/MP3/myMusic.mp3”; "/storage/emulated/sdcard/MP3/myMusic.mp3" 但它不起作用。

所以,我不知道是我没有使用正确的路径,还是 WWW.GetAudioClip() 方法在 Android 上不起作用。

对不起,我的英语不好,希望你能理解。我真的需要你的帮助。

【问题讨论】:

    标签: c# unity3d path mp3 android-sdcard


    【解决方案1】:

    问题是路径。您必须使用 C# FileInfoDirectoryInfo API 返回适当的路径,然后将该路径传递给 WWW API。将/mnt/sdcard 传递给DirectoryInfo API,它将为您提供正确的使用路径。使用WWW API 访问SD 卡上数据的路径是"file:///" + FileInfo.FullName.

    Blow 就是一个例子。它假定音乐 .mp3 文件放置在 SD 卡上名为 "music" 的文件夹中。如果它位于名为 "MP3" 的文件夹中,请将 "/mnt/sdcard/music" 更改为 "/mnt/sdcard/MP3" 确保转到 Build Settings for Android,更改 Write Permission 从内部外部(SDCard)

    public AudioSource aSource;
    
    public string path = @"/mnt/sdcard/music";
    private FileInfo[] info;
    private DirectoryInfo dir;
    
    IEnumerator LoadAndPlaySound()
    {
        //Get the proper path with DirectoryInfo
        dir = new DirectoryInfo(path);
        //Get all .mp3 files in the folder
        info = dir.GetFiles("*.mp3");
    
        //Use the first audio index found in the directory
        string audioPath = "file:///" + info[0].FullName;
    
        using (WWW www = new WWW(audioPath))
        {
            yield return www;
    
            //Set the AudioClip to the loaded one
            aSource.clip = www.GetAudioClip(false, false);
            //Play Audio
            aSource.Play();
        }
    }
    

    这是一个协程函数,所以你可以把它称为StartCoroutine(LoadAndPlaySound());

    【讨论】:

    • 非常感谢您快速而详细的回答!但是,它仍然不起作用..我把这个路径“/mnt/sdcard/MP3”但是我有这个错误:DirectoryNotFoundException: Directory 'C:\mnt\sdcard\MP3' not found。 Unity在路径开头加一个“C:”正常吗?
    • 您应该在您的 Android 上运行它,而不是在 Windows 上的编辑器中运行。这就是您看到该错误的原因
    • 我试过了,你是对的,我的 Android 设备上的路径是正确的,但没有任何反应。 mnt/sdcard/...是唯一的路径还是根据手机型号存在不同的路径?
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 2014-03-05
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多