2

我尝试在我的 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();
4

2 回答 2

3

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

于 2011-11-13T12:44:50.883 回答
3

您听到奇怪的噪音是正确的,因为您需要先对 MP3 进行解码,然后再将其输入 AudioTrack!AudioTrack 只播放原始 PCM 音频。

于 2011-07-20T12:03:13.893 回答