问题描述
我米做一个应用程序,这是应该打几个声音的媒体播放器。这是code我使用:
I m making an app which is supposed to play a few sounds with the mediaPlayer.This is the code i use :
String[] name = {"sonar_slow","sonar_medium","sonar_fast"};
String link = "/res/raw/" + name[state-1] + ".mp3";
try {
player.setDataSource(link);
player.prepare();
player.start();
} catch(Exception e) {
e.printStackTrace();
}
我也试过这样的:
I also tried this :
if(state==1){
player.create(this, R.raw.sonar_slow);
}else if(state==2){
player.create(this, R.raw.sonar_medium);
}else if(state==3){
player.create(this, R.raw.sonar_fast);
}
player.start();
但没有任何上述工作正常。我的应用程序没有崩溃,但声音是不是在玩。任何想法?
But none of the above is working. My app is not crashing but the sound is not playing.Any ideas ?
推荐答案
有两个问题。
您不能引用的资源在你的项目/ RES / raw目录以这种方式。在你的项目目录中的文件/res/raw/sonar_slow.mp3不是存储在你的apk/res/raw/sonar_slow.mp3。代替如下:
You cannot reference resources inside your projects /res/raw directory in this fashion. The file "/res/raw/sonar_slow.mp3" in your project directory is not stored in "/res/raw/sonar_slow.mp3" in your apk. Instead of the following:
MediaPlayer mp = MediaPlayer.create(this);
mp.setSource("sonar_slow");
您需要使用
MediaPlayer mp = MediaPlayer.create(this, R.raw.sonar_slow);
问题2
下面是错误的:它调用不会修改播放机的静态方法
player.create(this, R.raw.sonar_slow);
您应该改为调用
player = MediaPlayer.create(this, R.raw.sonar_slow);
完整的解决方案
下面是封装MediaPlayer的一个可重用的AudioPlayer类。这是稍微:大书呆子牧场指南Android的程序进行修改。它使一定要记得清理资源
Full solution
Below is a reusable AudioPlayer class that encapsulates MediaPlayer. This is slightly modified from "Android Programming: The Big Nerd Ranch Guide". It makes sure to remember to clean up resources
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public void play(Context c, int rid) {
stop();
mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
这篇关于从资源/原材料播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!