Playing a sound on button click with Android
我知道有人问过这个问题的一千个不同版本,我查看了它们并尝试了这些建议,但没有一个奏效。我试图在单击按钮时播放声音,同时在屏幕上显示新文本。当我按下按钮时,我会切换文本,但声音从不播放。这是我的代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public class MainActivity extends Activity {
Button button; @Override button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void toggleString(View v) { |
这是我的活动 xml 文件:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<TextView android:id="@+id/answer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="@string/nothing" android:textSize="40sp" android:layout_marginTop="40dp" /> <Button |
如果有人可以提供帮助,那就太好了。提前致谢。
编辑:这是我在尝试第二个建议后在控制台中看到的(这是打印堆栈吗?对不起,我不知道那是什么)
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
[2014–02–08 15:17:14 – ddmlib] An established connection was aborted by the software in your host machine java.io.IOException: An established connection was aborted by the software in your host machine at sun.nio.ch.SocketDispatcher.write0(Native Method) at sun.nio.ch.SocketDispatcher.write(Unknown Source) at sun.nio.ch.IOUtil.writeFromNativeBuffer(Unknown Source) at sun.nio.ch.IOUtil.write(Unknown Source) at sun.nio.ch.SocketChannelImpl.write(Unknown Source) at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213) at com.android.ddmlib.Client.sendAndConsume(Client.java:642) at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:348) at com.android.ddmlib.Client.requestAllocationStatus(Client.java:488) at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:835) at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:803) at com.android.ddmlib.DeviceMonitor.processIncomingJdwpData(DeviceMonitor.java:763) at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:652) at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:44) at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:580) [2014–02–08 15:19:44 – ddms] Can‘t bind to local 8600 for debugger |
您必须设置数据源并准备一次媒体播放器。
试试这个:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); AssetFileDescriptor afd; button.setOnClickListener(new OnClickListener() { @Override } catch (IllegalStateException e) { } |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#import android.media.MediaPlayer;
public class MainActivity extends Activity { MediaPlayer mySound; @Override |
尝试将声音文件保存在原始文件夹中,而不是资产,然后在活动中调用 MediaPlayer.create。在上面的示例中,原始文件夹中的声音文件名为 blop。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/267521.html