声音无法播放

问题描述 投票:0回答:2

我创建了一个简单的项目,其中一个布局包含两个按钮,这是我的代码:

package com.example.tessound;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener
{
    MediaPlayer player;
    Button play,mute;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        play = (Button)findViewById(R.id.button1);
        play.setOnClickListener(this);
        mute = (Button)findViewById(R.id.button2);
        mute.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onClick(View view)
    {
        if(view.getId()==R.id.button1)
        {
            playSound(1);
        }
        else if(view.getId()==R.id.button2)
        {
            playSound(2);
        }
    }

    public void playSound(int arg)
    {
        if (arg == 1)
        {
            player = MediaPlayer.create(this, R.raw.atur);
        }
        else if (arg == 2)
        {
            player = MediaPlayer.create(this, R.raw.back);
        }

        if(player != null)
        {
            player.setLooping(false);
            player.start();
        }

        try
        {
            if(player != null)
            {
                if (player.isPlaying()) 
                {
                    player.stop();
                    player.release();
                }
            }
        }
        catch(Exception e)
        {
        }
    }
}

当我尝试单击按钮时,声音无法播放。

android audio-player
2个回答
1
投票

遵循playSound方法的逻辑,参数值为1:

1)arg == 1所以:

player = MediaPlayer.create(this, R.raw.atur);

2)播放器已设置,因此不为空,因此:

player.setLooping(false);
player.start();

3)然后是你的尝试块。播放器不是空的并且正在播放,因此:

player.stop();
player.release();

所以我认为你正在开始播放,然后立即停止播放。我想你应该只在方法没有收到有效参数的情况下执行try / catch代码,即它应该是前面'if'语句的'else'。

编辑:

再看一遍,我认为try / catch代码应该放在方法的顶部。然后,在尝试开始播放新声音之前,它将停止播放器并释放它(如果它正在使用中)。逻辑上这是有道理的。


0
投票

使用Log跟踪控件并找到错误!

Log.e("AnyTAG","Description of the Log");

你的代码似乎没问题!

© www.soinside.com 2019 - 2024. All rights reserved.