美文网首页
unity加载下载播放MP3

unity加载下载播放MP3

作者: 萧非子 | 来源:发表于2017-11-30 11:10 被阅读43次

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.IO;
    using UnityEngine.UI;

    public class Downdload : MonoBehaviour
    {
    public AudioSource audioSource;
    string urlPath;//资源网络路径
    string file_SaveUrl;//资源保路径
    FileInfo file;
    public static Downdload instance;
    private bool p = true;
    private bool down;
    private float t;
    private float time;
    private void Awake()
    {
    instance = this;
    }
    private void Start()
    {
    time = 3;
    t = 0;
    }
    public void play()
    {
    urlPath = @"<span style="font-family: "Microsoft YaHei"; font-size: 14px; line-height: 21px;">http://m128.xiami.net/712/55712/2100253402/1775451414_59502672_l.mp3?auth_key=1508986800-0-0-eaddaaacb20bc6f1fe4dc8ee89ba0732</span>"<span style="font-family:Microsoft YaHei;"><span style="font-size: 14px;">;</span></span>
    file_SaveUrl = @"D:\Music\123.mp3";//保存的本地路径 记得加上文件后缀名
    file = new FileInfo(file_SaveUrl);
    Debug.Log(file_SaveUrl);
    DirectoryInfo mydir = new DirectoryInfo(file_SaveUrl);
    if (File.Exists(file_SaveUrl))//判断一下本地是否有了该音频 如果有就不需下载
    {
    string s = @"file://" + file_SaveUrl;
    StartCoroutine(LoadAudio(s));
    }
    else
    {
    StartCoroutine(DownFile(urlPath));
    }
    }
    IEnumerator DownFile(string url)
    {

        WWW www = new WWW(url);  
        down = false;  
        yield return www;  
        down = true;  
        if (www.isDone)  
        {  
            Debug.Log("下载完成");  
            byte[] bytes = www.bytes;  
            CreatFile(bytes);  
            string str = @"file://" + file_SaveUrl;  
            StartCoroutine(LoadAudio(str));  
        }  
    }  
    void CreatFile(byte[] bytes)  
    {  
        Stream stream;  
        stream = file.Create();  
        stream.Write(bytes, 0, bytes.Length);  
        stream.Close();  
        stream.Dispose();  
    }  
    public IEnumerator LoadAudio(string recordPath)  
    {  
        WWW www = new WWW(recordPath);  
        yield return www;  
        AudioClip ac = WWWAudioExtensions.GetAudioClip(www);  
        if (www.isDone)  
        {  
            audioSource.clip = ac;  
            audioSource.Play();  
        }  
    }  
    

    }

    相关文章

      网友评论

          本文标题:unity加载下载播放MP3

          本文链接:https://www.haomeiwen.com/subject/mefvbxtx.html