在Android上的Audiotrack上播放mp3的嗡嗡声

时间:2011-07-19 06:51:47

标签: android audio mp3 noise

我尝试在我的SDCard中为我的Android模拟器播放一个mp3文件,但所有出来的都是一些奇怪的嗡嗡声。我确定采样率是44.1k hz我不知道还有什么可能是错的

    if(AudioTrack.MODE_STATIC != mode && AudioTrack.MODE_STREAM != mode)
            throw new InvalidParameterException();

    String audioFilePath = "/sdcard/test.mp3";
    long fileSize = 0;
    long bytesWritten = 0;
    int bytesRead = 0;
    int bufferSize = 0;
    byte[] buffer;
    AudioTrack track;

            File audioFile = new File(audioFilePath);
            fileSize = audioFile.length();
    if(AudioTrack.MODE_STREAM == mode)
    {
            bufferSize = 8000;
    }
    else
    {// AudioTrack.MODE_STATIC
            bufferSize = (int)fileSize;
    }
    buffer = new byte[bufferSize];
    track = new AudioTrack(AudioManager.STREAM_MUSIC,/* this is for pcm*/ /*22050*/ /*this is for mp3*/ 44100, 
                            AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_DEFAULT/*AudioFormat.ENCODING_PCM_16BIT*/, 
                            bufferSize, mode);
    // in stream mode, 
    //   1. start track playback
    //   2. write data to track
    if(AudioTrack.MODE_STREAM == mode)
            track.play(); 
    FileInputStream audioStream = null;
    try {
                    audioStream = new FileInputStream(audioFile);
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            }

    while(bytesWritten < fileSize)
    {
            try {
                    bytesRead = audioStream.read(buffer, 0, bufferSize);
                    } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
            bytesWritten += track.write(buffer, 0, bytesRead);
    }
    // in static mode,
    //   1. write data to track
    //   2. start track playback
    if(AudioTrack.MODE_STATIC == mode)
            track.play();

2 个答案:

答案 0 :(得分:3)

你听到奇怪的声音是正确的,因为你需要先解码MP3 你把它喂给AudioTrack! AudioTrack只播放原始PCM音频。

答案 1 :(得分:3)

您应该使用android.media.MediaPlayer播放mp3音频文件