dam*_*shu 24 android media-player
我在我的Android应用程序的res/raw文件夹中有一个小(200kb)的mp3.我试图在Eclipse的模拟器中运行它.它被认为是R文件中的资源,但是当我尝试准备/启动时,我的活动崩溃了!还有其他我需要改变的东西,也许是在清单中吗?
MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
try {
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
// handle this later
}
Muh*_*hab 73
当启动活动时,即在onCreate上放下以下代码.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
mPlayer.start();
}
Run Code Online (Sandbox Code Playgroud)
当停止活动时,即在onDestroy上输入以下代码.
public void onDestroy() {
mPlayer.stop();
super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 :)
您可能更喜欢使用SoundPool类.它可以减少播放声音时的延迟,并提供其他细节,例如当一次播放太多时可以优先处理声音.
来自文档:
SoundPool是一组样本,可以从APK内部的资源或文件系统中的文件加载到内存中.SoundPool库使用MediaPlayer服务将音频解码为原始的16位PCM单声道或立体声流.这允许应用程序附带压缩流,而不必承受CPU负载和回放期间解压缩的延迟.
例如:
/**
* How many sounds can be played at once.
*/
private static final int MAX_SOUND_POOL_STREAMS = 4;
/**
* Modify this as part of your own priority scheme. Higher numbers mean higher
* priority. If you don't care, it's okay to use the same priority for every
* sound.
*/
private static final int NORMAL_PRIORITY = 10;
private int mySoundId;
@Override
public void setupContent() {
this.soundPool = new SoundPool(MAX_SOUND_POOL_STREAMS,
AudioManager.STREAM_MUSIC, 100);
this.mySoundId = this.soundPool.load(this.getApplicationContext(),
R.raw.mySound, 1);
}
@Override
private void playMySound() {
this.soundPool.play(this.mySoundId, 1, 1, NORMAL_PRIORITY, 0, 1);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76703 次 |
| 最近记录: |