Download Remote Audio File in Android Application

Download Remote Audio File in Android Application

In this tutorial, we are going to learn how to download a remote audio file in you android application. It is a simple application. The app user will copy the URL adress of the audio file into an EditText box and click on a button, then the audio file will be downloaded to store in the external storage system of the device.

In my previous tutorial, we covered how to record and play audio file. This can be a continuous or part of the application since it will give you the opportunity to download and play other audio file recorded by others.

In the app, we are going to create a Text box where users will copy the url address of file to download and a button when clicked will initiate the download process.

Now that we have a clearer idea on the kind of project we are doing, I will list the tools and resources I will use in this tutorial. Please feel free to use whatever tools, IDE and resources you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidVoiceRecording

Package: com.inducesmile.androidvoicerecording

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Finally, it is important for us to see the graphical user interface of the application we are building. The screen shot as shown below.

Download audio file

Open the main layout (activity_audio_link.xml). Copy and paste the following code.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.henry.voicerecognition.AudioLinkActivity">

    <TextView
        android:id="@+id/audio_heading"
        android:text="@string/audio_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="24dp"
        android:textColor="@color/primary_dark"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/audio_heading"
        android:layout_marginTop="16dp"
        android:textColor="@color/primary_text"
        android:text="@string/link_content"
        android:layout_alignParentLeft="true"
        android:id="@+id/textView" />

    <EditText
        android:id="@+id/audio_link"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:background="@drawable/border"
        android:layout_marginTop="32dp" />

    <Button
        android:id="@+id/download_audio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/download_audio"
        android:layout_below="@+id/audio_link"
        android:layout_centerHorizontal="true"
        android:background="@drawable/matchbutton"
        android:padding="16dp"
        android:layout_marginTop="32dp" />

    <Button
        android:id="@+id/select_match"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/select_file"
        android:layout_below="@+id/download_audio"
        android:layout_centerHorizontal="true"
        android:background="@drawable/matchbutton"
        android:padding="16dp"
        android:layout_marginTop="40dp" />


    <ProgressBar
        android:id="@+id/progress_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:indeterminate="true"
        android:max="100"
        android:minHeight="50dp"
        android:minWidth="200dp"
        android:progress="1"
        android:visibility="gone"
        android:layout_centerVertical="true" />

</RelativeLayout>

In the code above, we are going to make use of TextView, EditView, Button and ProgressBar view controls.

The TextView is basically use for instruction on how to use the application. The EditText is use to get user input which should equate to a valid remote URL of the audio file you want to download.

Since we are going to make a network call, we will use android AsyncTask to download the audio file download in a different thread. This is important so that our download process will not interfer with the main UI thread.

Now let move on to the Activity file of our corresponding layout (AudioLinkActivity.java). Open the file, we are going to get some of our views handle by using the Activity class method findViewById(int id);

When a button is click, if the user did not entered any link, the application will instruct the user to do so first. Otherwise, we will get the entered remote URL address and pass it as a parameter to our AsyncTask class method execute(String url);

The complete code snippet for the code is pasted below. You can copy and paste it in your application.

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class AudioLinkActivity extends AppCompatActivity{

    private EditText audioText;
    private String downloadAudioPath;
    private String urlDownloadLink = "";

    private ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_link);

        downloadAudioPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        File audioVoice = new File(downloadAudioPath + File.separator + "voices");
        if(!audioVoice.exists()){
            audioVoice.mkdir();
        }

        progressbar = (ProgressBar)findViewById(R.id.progress_view);
        audioText = (EditText)findViewById(R.id.audio_link);
        Button selectMatch = (Button)findViewById(R.id.select_match);
        selectMatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent selectIntent = new Intent(AudioLinkActivity.this, SelectAudioActivity.class);
                startActivity(selectIntent);
            }
        });

        Button audioLinkButton = (Button)findViewById(R.id.download_audio);

        audioLinkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                urlDownloadLink = audioText.getText().toString();
                if(urlDownloadLink.equals("")){
                    Toast.makeText(AudioLinkActivity.this, "Please add audio download link", Toast.LENGTH_LONG).show();
                    return;
                }
                String filename = extractFilename();
                downloadAudioPath = downloadAudioPath + File.separator + "voices" + File.separator + filename;
                DownloadFile downloadAudioFile = new DownloadFile();
                downloadAudioFile.execute(urlDownloadLink, downloadAudioPath);
                audioText.setText("");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_audio_link, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... url) {
            int count;
            try {
                URL urls = new URL(url[0]);
                URLConnection connection = urls.openConnection();
                connection.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = connection.getContentLength();

                InputStream input = new BufferedInputStream(urls.openStream());
                OutputStream output = new FileOutputStream(url[1]);

                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;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressbar.setVisibility(ProgressBar.VISIBLE);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressbar.setVisibility(ProgressBar.GONE);
        }
    }

    private String extractFilename(){
        if(urlDownloadLink.equals("")){
            return "";
        }
        String newFilename = "";
        if(urlDownloadLink.contains("/")){
            int dotPosition = urlDownloadLink.lastIndexOf("/");
            newFilename = urlDownloadLink.substring(dotPosition + 1, urlDownloadLink.length());
        }
        else{
            newFilename = urlDownloadLink;
        }
        return newFilename;
    }
}

That brings us to the end of our tutorial. If you want to integrate it with our previous tutorial, the best way will be to create a new Activity page were you can list all the downloaded audio file then you can select which audio file you will like to listen to.

Now, when you run your application you will see the application interface and how it looks like.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

If you like this tutorial, please support me by kindly download my new android app in Google play store by clicking the image below

bannerad

2 Comments

    • Inducesmile

Add a Comment