如何在android系统播放声音从服务器 [英] How to play audio from server in android

查看:249
本文介绍了如何在android系统播放声音从服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器获取所有音频文件列表,列表视图按照code。

 公共类ServerFileList延伸活动{    URL urlAudio;
    ListView的mListView;
    ProgressDialog pDialog;
    私人MediaPlayer的熔点为新的MediaPlayer();
    私人列表<串GT; myList中=新的ArrayList<串GT;();    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.serverfilelist);        mListView =(ListView控件)findViewById(R.id.listAudio);
        新getAudiofromServer()执行();
        新downloadAudioFromServer()执行();        mListView.setOnItemClickListener(新OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,
                    INT位置,长的id){
                playSong(urlAudio + myList.get(位置));
            }
        });
    }    私人无效playSong(字符串songPath){
        尝试{
            mp.reset();
            mp.setDataSource(songPath);
            MP prepare()。
            mp.start();
        }赶上(IOException异常五){
            Log.v(的getString(R.string.app_name),e.getMessage());
        }
    }    私有类downloadAudioFromServer扩展
            AsyncTask的<字符串,整数,字符串> {
        @覆盖
        保护字符串doInBackground(字符串... URL){
            诠释计数;            尝试{
                网址为url1 =新的URL(http://i-qualtech.com/Fidol/uploadAudio);
                URLConnection的conexion = url1.openConnection();
                conexion.connect();
                INT lenghtOfFile = conexion.getContentLength();
                InputStream的输入=新的BufferedInputStream(url1.openStream());
                OutputStream的输出=新的FileOutputStream(
                        Environment.getExternalStorageDirectory()+/声音/);
                字节的数据[] =新的字节[1024];
                总长= 0;                而((计数= input.read(数据))!= - 1){
                    总+ =计数;
                    //发布进度....
                    publishProgress((int)的(总* 100 / lenghtOfFile));
                    output.write(数据0,计);
                }                output.flush();
                output.close();
                input.close();
            }赶上(例外五){
            }
            返回null;
        }
    }    类getAudiofromServer扩展的AsyncTask<字符串,字符串,字符串> {
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(ServerFileList.this);
            pDialog.setMessage(从服务器获取文件列表中,请稍候......);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(假);
            pDialog.show();
        }        @燮pressWarnings(未登记)
        @覆盖
        保护字符串doInBackground(字符串...为arg0){
            尝试{
                urlAudio =新的URL(http://i-qualtech.com/Fidol/uploadAudio);
            }赶上(MalformedURLException的E){
                e.printStackTrace();
            }
            ApacheURLLister lister1 =新ApacheURLLister();
            尝试{
                myList中= lister1.listAll(urlAudio);
            }赶上(IOException异常五){
                e.printStackTrace();
            }
            返回null;
        }        保护无效onPostExecute(字符串FILE_URL){
            如果(pDialog.isShowing()){
                pDialog.dismiss();
            }            ArrayAdapter<串GT;适配器=新ArrayAdapter<串GT;(
                    ServerFileList.this,android.R.layout.simple_list_item_1,
                    myList中);
            adapter.notifyDataSetChanged();
            mListView.setAdapter(适配器);
            mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            mListView.setCacheColorHint(Color.TRANSPARENT);
        }
    }
}

和输出

现在我想通过点击列表视图为发挥这一音频文件写道:我已经有我上面列出的code,但我收到以下错误。

我已经提到以下链接为参考。

如何从服务器

如何从Android的服务器

但在这两个链路他们指定特定的音频文件从服务器上玩,给予了充分的路径,但我不想这样做。

我知道这显然是说,我不能投的URL字符串,但我不知道我怎样才能解决这个问题。请帮助。

  1月二日至5日:44:58.690:E / AndroidRuntime(1998年):致命异常:主要
1月2日至5日:44:58.690:E / AndroidRuntime(1998):java.lang.ClassCastException:java.net.URL中不能转换为java.lang.String
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在iqual.fidol_final.ServerFileList $ 1.onItemClick(ServerFileList.java:53)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.widget.AdapterView.performItemClick(AdapterView.java:298)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.widget.AbsListView.performItemClick(AbsListView.java:1100)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.widget.AbsListView $ PerformClick.run(AbsListView.java:2788)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.widget.AbsListView $ 1.run(AbsListView.java:3463)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.os.Handler.handleCallback(Handler.java:730)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.os.Handler.dispatchMessage(Handler.java:92)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.os.Looper.loop(Looper.java:137)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在android.app.ActivityThread.main(ActivityThread.java:5103)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在java.lang.reflect.Method.invokeNative(本机方法)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在java.lang.reflect.Method.invoke(Method.java:525)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
1月2日至5日:44:58.690:E / AndroidRuntime(1998):在dalvik.system.NativeStart.main(本机方法)


我设法解决这个问题,只需添加一块低于code到我onItemClicklistner,它工作正常现在,

 字符串URL = NULL;
对象o = myList.get(位置);
URL = o.toString()代替(,%20)修剪()。
玩=(PlaySongAsy)新PlaySongAsy(URL).execute();

I am getting all audio file list from server to list-view by following code.

public class ServerFileList extends Activity {

    URL urlAudio;
    ListView mListView;
    ProgressDialog pDialog;
    private MediaPlayer mp = new MediaPlayer();
    private List<String> myList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.serverfilelist);

        mListView = (ListView) findViewById(R.id.listAudio);
        new getAudiofromServer().execute();
        new downloadAudioFromServer().execute();

        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                playSong(urlAudio + myList.get(position));
            }
        });
    }

    private void playSong(String songPath) {
        try {
            mp.reset();
            mp.setDataSource(songPath);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            Log.v(getString(R.string.app_name), e.getMessage());
        }
    }

    private class downloadAudioFromServer extends
            AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... url) {
            int count;

            try {
                URL url1 = new URL("http://i-qualtech.com/Fidol/uploadAudio");
                URLConnection conexion = url1.openConnection();
                conexion.connect();
                int lenghtOfFile = conexion.getContentLength();
                InputStream input = new BufferedInputStream(url1.openStream());
                OutputStream output = new FileOutputStream(
                        Environment.getExternalStorageDirectory() + "/Sounds/");
                byte data[] = new byte[1024];
                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;
        }
    }

    class getAudiofromServer extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ServerFileList.this);
            pDialog.setMessage("Getting File list from server, Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected String doInBackground(String... arg0) {
            try {
                urlAudio = new URL("http://i-qualtech.com/Fidol/uploadAudio");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            ApacheURLLister lister1 = new ApacheURLLister();
            try {
                myList = lister1.listAll(urlAudio);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String file_url) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    ServerFileList.this, android.R.layout.simple_list_item_1,
                    myList);
            adapter.notifyDataSetChanged();
            mListView.setAdapter(adapter);
            mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            mListView.setCacheColorHint(Color.TRANSPARENT);
        }
    }
}

And the output is

Now i want to play that audio file by clicking list-view for that i wrote code that already i have listed above but i am getting following error.

I have referred below link for the reference.

How to play Audio file Mp3 from the server

how to play audio file from server in android

But in this both link they have specified particular audio file to play from server and given full path but i don't want to do that.

I know it is clearly saying that I can not cast URL to String, But i don't know how can i solve this. please help.

02-05 01:44:58.690: E/AndroidRuntime(1998): FATAL EXCEPTION: main
02-05 01:44:58.690: E/AndroidRuntime(1998): java.lang.ClassCastException: java.net.URL cannot be cast to java.lang.String
02-05 01:44:58.690: E/AndroidRuntime(1998):     at iqual.fidol_final.ServerFileList$1.onItemClick(ServerFileList.java:53)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.widget.AbsListView$1.run(AbsListView.java:3463)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.os.Handler.handleCallback(Handler.java:730)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.os.Looper.loop(Looper.java:137)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at android.app.ActivityThread.main(ActivityThread.java:5103)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at java.lang.reflect.Method.invokeNative(Native Method)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at java.lang.reflect.Method.invoke(Method.java:525)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-05 01:44:58.690: E/AndroidRuntime(1998):     at dalvik.system.NativeStart.main(Native Method)

解决方案

I have managed to solve this problem, Just added below piece of code to my onItemClicklistner and it is working fine now,

String url = null;
Object o = myList.get(position);
url = o.toString().replace(" ", "%20").trim();
play = (PlaySongAsy) new PlaySongAsy(url).execute();

这篇关于如何在android系统播放声音从服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆