玩在Java中的声音效果 [英] Playing a Sound Effect in Java

查看:146
本文介绍了玩在Java中的声音效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做这行code的等效,只是用一个小的mp3文件系统提示音:

I'm trying to do the equivalent of this line of code, except substituting a small mp3 file for the system beep:

Toolkit.getDefaultToolkit().beep();

我有了,我想打一个小音效的MP3文件。这是一个相对容易的事?有人能告诉我code做到这一点?

I have an mp3 file that has a little sound effect that I want to play. Is this a relatively easy thing to do? Can somebody show me the code to do this?

推荐答案

您可以使用的MediaPlayer播放声音。以下是我通常用我所有的音频。

You could use MediaPlayer to play the sound. Here is what I usually use for all my audio.

public class APP extends Activity {

//ADD THIS LINE AND IMPORT MediaPlayer
MediaPlayer btnClick;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ADD THIS LINE TO YOUR onCreate METHOD AFTER YOU SET THE CONTENT VIEW
btnClick = MediaPlayer.create(this, R.raw.button_click);
    }
}

此设置您的音频和它应该发挥什么样的。直到它完成它会播放你的声音。那么这行添加到任何你想要的声音播放:

This sets up your audio and what it should play. It will play your sound until it is finished. Then add this line to wherever you want the sound to play:

btnClick.start();

如果你想要再循环(配乐或歌曲),补充一点:

If you want it to loop (a soundtrack or song), add this:

btnClick.setLooping(true);

一旦你与​​你循环,或者您与应用程序完成了配乐完成后,将它添加到停止音频:

Once you are finished with the soundtrack that you looped or you are finished with the application, add this to stop the audio:

btnClick.stop();

btnClick.release();

所以,在技术上你会增加2线,为自己的MediaPlayer,1行启动它,1号线结束它(可选的,但最好的良好的编程习惯和做法)。

So technically you would be adding 2 lines for the MediaPlayer itself, 1 line to start it, and 1 line to end it (optional but best for good programming habits and practices).

我希望这彻底地回答你的问题。干杯!

I hope this thoroughly answers your question. Cheers!

这篇关于玩在Java中的声音效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆