【发布时间】:2025-12-21 09:20:16
【问题描述】:
尝试播放我的 mp3 时没有声音。我需要在清单中启用某些东西吗? 我找到了一些刚刚创建媒体播放器并调用 start 的示例。
我只在调用 stop 后才调用 prepare。
每次按下播放按钮时,日志都会显示 2 条开始消息和 2 条停止消息。为什么是 2?
代码:
package com.xx.yy;
import java.io.IOException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainMenuFragment extends Fragment implements OnClickListener
{
private MediaPlayer mediaPlayer;
private boolean pressed = false;
private boolean stopped = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate( R.layout.main_menu_layout, container, false );
view.setBackgroundResource( 0 );
Button play = (Button) view.findViewById( R.id.play_button );
play.setOnClickListener( this );
mediaPlayer = MediaPlayer.create( getActivity(), R.raw.qa2pir_projektrespekt );
return view;
}
@Override
public void onClick( View view )
{
if ( !pressed )
{
try
{
if ( stopped )
{
mediaPlayer.prepare();
}
mediaPlayer.start();
pressed = true;
}
catch ( IllegalStateException e )
{
Log.d( "IllegalState", e.toString() );
}
catch ( IOException e )
{
Log.d( "IO", e.toString() );
}
}
else
{
mediaPlayer.stop();
pressed = false;
stopped = true;
}
}
}
布局:
<LinearLayout 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:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/play_button"
android:background="@color/black"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="75dp"
android:layout_marginBottom="0dp"
android:textColor="@color/white"
android:textSize="25sp"
android:textStyle="bold"
android:text="@string/play"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
/>
</LinearLayout>
清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xx.yy"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:label="@string/app_name" android:name="com.sj.replicator.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
【问题讨论】:
标签: android mp3 android-mediaplayer