我正在使用这个库:https ://github.com/alxrm/audiowave-progressbar来提供像 Soundcloud 音乐播放器一样的音频波效果。
这就是我实现的方式:
byte[] data = convert(songsList.get(currentSongIndex).get("songPath"));
final AudioWaveView waveView = (AudioWaveView) findViewById(R.id.wave);
waveView.setScaledData(data);
waveView.setRawData(data, new OnSamplingListener() {
@Override
public void onComplete() {
}
});
waveView.setOnProgressListener(new OnProgressListener() {
@Override
public void onStartTracking(float progress) {
}
@Override
public void onStopTracking(float progress) {
}
@Override
public void onProgressChanged(float progress, boolean byUser) {
}
});
这是使用所述文件的路径将文件转换为字节数组的方法
public byte[] convert(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1;) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
也许问题是由于没有异步获取数组,但我不确定。
谁能帮我这个?
编辑:正如@commonsware 正确建议的那样,我这样做了:
class AudioWave extends AsyncTask<String,Integer,String>{
private Context mContext;
private View rootView;
public MusicPlayerActivity m;
final AudioWaveView waveView = (AudioWaveView) m.findViewById(R.id.wave);
public AudioWave(MusicPlayerActivity m1){
m = m1;
}
// Runs in UI before background thread is called
@Override
protected void onPreExecute() {
super.onPreExecute();
// Do something like display a progress bar
}
byte[] b2;
// This is run in a background thread
@Override
protected String doInBackground(String... params){
// get the string from params, which is an array
String path = params[0];
try {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
try {
for (int readNum; (readNum = fis.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
}catch(IOException e){
}
byte[] bytes = bos.toByteArray();
b2=bytes;
new MusicPlayerActivity().setData(b2);
}
catch (FileNotFoundException e){
}
return "lol";
}
// This is called from background thread but runs in UI
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
@Override
protected void onPostExecute(String result) {
waveView.setScaledData(b2);
waveView.setRawData(b2, new OnSamplingListener() {
@Override
public void onComplete() {
}
});
waveView.setOnProgressListener(new OnProgressListener() {
@Override
public void onStartTracking(float progress) {
}
@Override
public void onStopTracking(float progress) {
}
@Override
public void onProgressChanged(float progress, boolean byUser) {
}
});
super.onPostExecute(result);
// Do things like hide the progress bar or change a TextView
}
}