📜  如何在Android中清除或释放音频资源?

📅  最后修改于: 2021-05-13 16:08:21             🧑  作者: Mango

随着对Android中内存消耗的优先级提高,如果应用程序使用Mediaplayer API,则会分配大部分内存资源。当不再需要Mediaplayer实例时或在完成播放媒体资源文件后,开发人员需要注意。因此,在本文中,已逐步讨论了如何在各种情况下释放媒体播放器资源,以便稳定应用程序的内存消耗。

释放音频资源的步骤

第1步:创建一个空的Activity Android Studio项目。

  • 创建一个空的活动Android Studio项目。
  • 参考Android |如何在Android Studio中创建/启动新项目?关于如何创建一个清空活动的Android Studio项目。注意,我们将使用Java语言来实现该项目。

步骤2:准备要播放的示例音频文件。

  • 在这种情况下,将在原始文件夹中获取一个示例MP3文件。
  • 要创建“ raw 文件夹,请右键单击“ Res >“新建”>“ Android资源目录”,然后选择资源类型作为Raw。
  • 在创建文件夹后,添加一些示例音频文件进行播放。
  • 如果无法完成上述步骤,请参考以下视频。

步骤3:使用activity_main.xml

  • activity_main.xml文件中,实现了一个简单的“播放”按钮,单击该按钮即可开始播放音频文件。
  • 调用以下代码。
XML


  
    
    
    


Java
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Mediaplayer instance to initiate the audio file to play
    MediaPlayer mediaPlayer;
  
    // Button instance to handle the PLAY button
    Button bPlay;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
  
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
  
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });
    }
}


Java
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Mediaplayer instance to initiate 
      // the audio file to play
    MediaPlayer mediaPlayer;
  
    // Button instance to handle the PLAY button
    Button bPlay;
  
    // Implement the on completion listener callback to do the 
      // actions on the media player instance
    // when the audio file gets completely played
    MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayerResources();
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
  
        // prepare the audio file for 
          // mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
  
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
  
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }
  
    // dedicated function is made to check the 
      // mediaPlayer instance is null or not
    // based on that the actions are taken on
      // the mediaPlayer instance
    void releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
  
            // it is safe to stop playing the audio 
              // file before releasing the audio file
            mediaPlayer.stop();
  
            // after stop playing the audio file 
              // release the audio resources
            mediaPlayer.release();
        }
    }
}


Java
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Mediaplayer instance to initiate the audio file to play
    MediaPlayer mediaPlayer;
  
    // Button instance to handle the PLAY button
    Button bPlay;
  
    // Implement the on completion listener callback to do 
      // the actions on the media player instance
    // when the audio file gets completely played
    MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayerResources();
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
  
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
  
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
  
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }
  
    @Override
    protected void onStop() {
  
        // Before going to stop state release the 
          // allocated mediaplyer resources
        releaseMediaPlayerResources();
  
        super.onStop();
    }
  
    // dedicated function is made to check the 
      // mediaPlayer instance is null or not
    // based on that the actions are taken 
      // on the mediaPlayer instance
    void releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
  
            // it is safe to stop playing the audio file 
              // before releasing the audio file
            mediaPlayer.stop();
  
            // after stop playing the audio file 
              // release the audio resources
            mediaPlayer.release();
        }
    }
}


输出界面:

在Android中清除或释放音频资源

步骤4:使用MainActivity。 Java文件

  • 使用原始资源启动MediaPlayer实例以播放音频文件。
  • 调用以下代码来处理播放按钮,以开始播放音频文件。
  • 在代码中添加了注释,以更好地理解。

Java

import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Mediaplayer instance to initiate the audio file to play
    MediaPlayer mediaPlayer;
  
    // Button instance to handle the PLAY button
    Button bPlay;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
  
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
  
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
            }
        });
    }
}

输出:在模拟器上运行

可以释放或清除音频资源的各种方案

方案1:完全播放音频文件后

  • 这是可以释放音频资源的方案之一。
  • 在这种情况下,在完全播放音频文件后释放资源。
  • 调用以下代码为mediaPlayer实例实现完成时侦听器,并释放Audio资源。

Java

import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Mediaplayer instance to initiate 
      // the audio file to play
    MediaPlayer mediaPlayer;
  
    // Button instance to handle the PLAY button
    Button bPlay;
  
    // Implement the on completion listener callback to do the 
      // actions on the media player instance
    // when the audio file gets completely played
    MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayerResources();
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
  
        // prepare the audio file for 
          // mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
  
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
  
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }
  
    // dedicated function is made to check the 
      // mediaPlayer instance is null or not
    // based on that the actions are taken on
      // the mediaPlayer instance
    void releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
  
            // it is safe to stop playing the audio 
              // file before releasing the audio file
            mediaPlayer.stop();
  
            // after stop playing the audio file 
              // release the audio resources
            mediaPlayer.release();
        }
    }
}

方案2:当用户按下“后退”或“主页”按钮时。

  • 如果应用程序是新闻阅读或播客类型,则只要用户按下“后退”按钮或“主页”按钮,该应用程序将处于“停止”状态。
  • 因此,在这种情况下,需要重写onStop方法,并释放或清除分配的音频资源。
  • 将以下代码调用到MainActivity。 Java文件。

Java

import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Mediaplayer instance to initiate the audio file to play
    MediaPlayer mediaPlayer;
  
    // Button instance to handle the PLAY button
    Button bPlay;
  
    // Implement the on completion listener callback to do 
      // the actions on the media player instance
    // when the audio file gets completely played
    MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayerResources();
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register the PLAY button with appropriate id.
        bPlay = findViewById(R.id.play_button);
  
        // prepare the audio file for mediaPlayer instance to play it.
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
  
        // handle the play button
        bPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
  
                mediaPlayer.setOnCompletionListener(onCompletionListener);
            }
        });
    }
  
    @Override
    protected void onStop() {
  
        // Before going to stop state release the 
          // allocated mediaplyer resources
        releaseMediaPlayerResources();
  
        super.onStop();
    }
  
    // dedicated function is made to check the 
      // mediaPlayer instance is null or not
    // based on that the actions are taken 
      // on the mediaPlayer instance
    void releaseMediaPlayerResources() {
        if (mediaPlayer != null) {
  
            // it is safe to stop playing the audio file 
              // before releasing the audio file
            mediaPlayer.stop();
  
            // after stop playing the audio file 
              // release the audio resources
            mediaPlayer.release();
        }
    }
}

当按下主页按钮时,音频应停止。如下所示:

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