android - 如何在点击按钮时播放声音

标签 android

我试图通过单击按钮在模拟器上播放声音文件,但我收到消息“应用程序播放音频意外停止”

我的代码是:

package com.java4u.android;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public  class p1 extends Activity {


// creating instance of media player
MediaPlayer mp=MediaPlayer.create(this,R.raw.meow);
@Override
protected void onCreate(Bundle savedInstanceState) 
{    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btnSound=(Button)this.findViewById(R.id.playSound);

    btnSound.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        startActivity(new Intent("com.java4u.android.p1")); 
            mp.start();
        }
    }); 

        }

}

list .xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.java4u.android"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".p1" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

主.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:text="play audio" 
    android:id="@+id/playSound" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
    </Button>
</LinearLayout>

最佳答案

试试这个:

Button btn1=(Button)findViewById(R.id.xBtn1);

btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.fruit_dance);  
        mp1.start();
    }
}

关于android - 如何在点击按钮时播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394422/

相关文章:

android - 错误 : cordova-res was not found on your PATH

android - 对于需要 Google 电子钱包商家帐户才能启用应用内结算感到困惑

java - Android:带有重复项的 SortedList

Android MediaCodec 和 GLSurfaceView

android - 如何在android中获取设备的温度

android - 从 Assets 中检索图像时出错

android - 将 S3 TransferUtility 与 Content Uri 结合使用

Android Studio 0.8.14 无法解析符号 'Bundle'

android - TextView - 以编程方式设置文本大小似乎不起作用

android - EAS 构建失败,错误代码为 1,但 Expo Build 成功,我需要 EAS 构建来删除未使用的包,如 com.segment.analytics.android :analytics