媒体播放器无法在Android中运行

时间:2013-09-16 15:21:28

标签: android audio spinner

想法是单击微调器,让它给你一个播放声音的时间列表。一旦你选择了一个声音,然后点击它应该播放的按钮。它不起作用,我无法弄清楚为什么。我有一个主屏幕和一个家庭活动,当你点击一个按钮带你进入一个新的活动和一个新的布局。我可以加载新的布局和新活动,这是下面的特色,但声音和微调器没有启动。

package com.androidsleepmachine.gamble;

package com.androidsleepmachine.gamble;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View; 
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class Ship extends Activity implements View.OnClickListener {
public static final int[] TIME_IN_MINUTES = { 30, 45, 60 };
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Button button1;
public Spinner spinner1;

// Initialize the activity
@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.ship);

    button1 = (Button) findViewById(R.id.btnSubmit);
    button1.setOnClickListener(this);
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,   
            android.R.layout.simple_spinner_item);
}

// Play the sound and start the timer
private void playSound(int resourceId) {
    // Cleanup any previous sound files
    cleanup();
    // Create a new media player instance and start it
    mediaPlayer = MediaPlayer.create(this, resourceId);
    mediaPlayer.start();
    // Create the timer to stop the sound after x number of milliseconds
    int selectedTime = TIME_IN_MINUTES[spinner1.getSelectedItemPosition()];
    handler.postDelayed(runnable, selectedTime * 60 * 1000);
}

// Handle button callbacks
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnSubmit:
            playSound(R.raw.ocean_ship);
            break;
    }
}

// Stop the sound and cleanup the media player
public void cleanup() {
    if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }
    // Cancel any previously running tasks
    handler.removeCallbacks(runnable);
}

// Runnable task used by the handler to stop the sound
public Runnable runnable = new Runnable() {
    public void run() {
        cleanup();
    }
};

}

2 个答案:

答案 0 :(得分:1)

问题出现在你的switch statemenet中。您正在检查id button1 listener,但您button1所指定的唯一按钮是id btnSubmit playSound() }。所以你的onClick()函数永远不会被调用。

// Handle button callbacks @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnSubmit: playSound(R.raw.ocean_ship); break; } } 更改为

ArrayAdapter

修改

为您的ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, TIME_IN_MINUTES); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(adapter); 尝试类似

的内容
{{1}}

答案 1 :(得分:0)

你是在模拟器上做这个吗? Mediaplayer不能在模拟器上运行。您必须在真实设备中测试它。