通过onclicklistener按钮播放声音

时间:2018-08-26 18:27:04

标签: onclick playsound

我想通过单击一个按钮来播放声音。我写了一个代码,并以此代码播放了声音,但是当我单击相同的按钮时,应用程序崩溃了。(错误是致命异常主进程“ packagename”),代码在这里。 请原谅我英语不好...

package com.yasi.moharram;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.IOException;

public class sound extends AppCompatActivity {
    public final MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sound);
        final Button btnsound1 = (Button) findViewById(R.id.btnsound1);
        final Button btnsound2 = (Button) findViewById(R.id.btnsound2);
        //btnsound2.setVisibility(View.INVISIBLE);


        btnsound1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view ) {
                Uri myuri = Uri.parse("http://cdn2.ahlolbait.ir/files/download/nazarqatari.mp362553.mp3");
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(G.context,myuri);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //btnsound1.setVisibility(View.INVISIBLE);
                //btnsound2.setVisibility(View.VISIBLE);

            }


        });
        btnsound2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        mediaPlayer.stop();
        mediaPlayer.release();

    }
}

0 个答案:

没有答案