尝试播放我的mp3时没有声音。我是否需要在清单中启用某些内容? 我找到了一些刚创建了媒体播放器的例子,并称之为start。
我只能在停止呼叫后调用准备。
每次按下播放按钮时,日志显示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>
答案 0 :(得分:0)
MediaPlayer mPlayer= MediaPlayer.create(getActivity().getApplicationContext(), com.cea_new.R.raw.c2hindi);;
mPlayer.start();
试试这个代码。“com.cea_new”是我的包名,所以用你的包名替换它。
这里R.raw.filename不起作用,因为它是活动中的一个片段,只有R.raw.filename可以工作