📜  如何从Android中的URL播放音频?

📅  最后修改于: 2021-05-10 16:40:49             🧑  作者: Mango

许多应用程序都要求该功能在其应用程序中添加音频功能,因此我们必须在应用程序中播放如此多的音频文件。如果我们将大量音频文件存储在我们的应用程序中,那么它将增加应用程序的大小,并且由于庞大的应用程序大小,这可能会减少用户群。因此,解决此问题的更好方法是将音频文件存储在数据库中,并从其唯一的Web URL访问它们。在本文中,我们将介绍如何在Android中播放来自URL的音频文件。

我们将在此应用程序中构建什么?

我们将构建一个简单的应用程序,在其中将显示两个用于播放和暂停音频的按钮。我们将从URL加载该音频。下面是视频,我们将在其中观看我们将要构建的内容。现在,让我们开始实施。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML


  
    
    


XML



Java
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for 
    // button and media player
    Button playBtn, pauseBtn;
    MediaPlayer mediaPlayer;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing our buttons
        playBtn = findViewById(R.id.idBtnPlay);
        pauseBtn = findViewById(R.id.idBtnPause);
          
        // setting on click listener for our play and pause buttons.
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method to play audio.
                playAudio();
            }
        });
          
        pauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking the media player 
                // if the audio is playing or not.
                if (mediaPlayer.isPlaying()) {
                    // pausing the media player if media player 
                    // is playing we are calling below line to
                    // stop our media player.
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.release();
                      
                    // below line is to display a message 
                    // when media player is paused.
                    Toast.makeText(MainActivity.this, "Audio has been paused", Toast.LENGTH_SHORT).show();
                } else {
                    // this method is called when media 
                    // player is not playing.
                    Toast.makeText(MainActivity.this, "Audio has not played", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
  
    private void playAudio() {
  
        String audioUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
          
        // initializing media player
        mediaPlayer = new MediaPlayer();
          
        // below line is use to set the audio 
        // stream type for our media player.
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  
        // below line is use to set our 
        // url to our media player.
        try {
            mediaPlayer.setDataSource(audioUrl);
            // below line is use to prepare
            // and start our media player.
            mediaPlayer.prepare();
            mediaPlayer.start();
  
        } catch (IOException e) {
            e.printStackTrace();
        }
        // below line is use to display a toast message.
        Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
    }
}


步骤3:向AndroidManifest.xml文件添加权限

由于我们正在从android中的URL播放音频。因此,我们将必须添加Internet权限才能加载URL。将以下权限添加到AndroidManifest.xml文件。

XML格式




步骤4:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for 
    // button and media player
    Button playBtn, pauseBtn;
    MediaPlayer mediaPlayer;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing our buttons
        playBtn = findViewById(R.id.idBtnPlay);
        pauseBtn = findViewById(R.id.idBtnPause);
          
        // setting on click listener for our play and pause buttons.
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method to play audio.
                playAudio();
            }
        });
          
        pauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking the media player 
                // if the audio is playing or not.
                if (mediaPlayer.isPlaying()) {
                    // pausing the media player if media player 
                    // is playing we are calling below line to
                    // stop our media player.
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.release();
                      
                    // below line is to display a message 
                    // when media player is paused.
                    Toast.makeText(MainActivity.this, "Audio has been paused", Toast.LENGTH_SHORT).show();
                } else {
                    // this method is called when media 
                    // player is not playing.
                    Toast.makeText(MainActivity.this, "Audio has not played", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
  
    private void playAudio() {
  
        String audioUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";
          
        // initializing media player
        mediaPlayer = new MediaPlayer();
          
        // below line is use to set the audio 
        // stream type for our media player.
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  
        // below line is use to set our 
        // url to our media player.
        try {
            mediaPlayer.setDataSource(audioUrl);
            // below line is use to prepare
            // and start our media player.
            mediaPlayer.prepare();
            mediaPlayer.start();
  
        } catch (IOException e) {
            e.printStackTrace();
        }
        // below line is use to display a toast message.
        Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
    }
}

添加代码后,现在运行您的应用程序并查看该应用程序的输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!