android 播放源文件中的mp3详细代码
时间: 2023-10-07 07:12:38 浏览: 53
以下是一个简单的 Android 播放本地 MP3 文件的示例代码:
1. 在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
2. 在布局文件中添加一个 Button 控件:
```xml
<Button
android:id="@+id/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />
```
3. 在 Activity 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private Button btnPlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = findViewById(R.id.btn_play);
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.my_mp3_file);
}
mediaPlayer.start();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
```
在上面的代码中,我们首先在 onCreate() 方法中获取 Button 控件,并在点击时播放指定的 MP3 文件。当 Activity 销毁时,我们需要释放 MediaPlayer 对象以便能够正确地释放系统资源。
请注意,我们使用了 MediaPlayer.create() 方法来创建 MediaPlayer 对象并指定要播放的 MP3 文件。在这个示例中,我们将 MP3 文件放在了 res/raw 目录中,并在 R 文件中生成了一个对应的资源 ID。如果您的 MP3 文件不在这个目录中,您需要使用其他方法来获取文件的路径。例如,您可以使用 File 类和 Environment.getExternalStorageDirectory() 方法来获取外部存储设备上的文件路径。
希望这个示例对您有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)