Android Studio中的Java MediaPlayer仅播放一秒钟的音频,然后停止。

huangapple go评论72阅读模式
英文:

Android Studio Java MediaPlayer plays only the first second of audio and then stops

问题

我尝试让MediaPlayer播放大约两分钟长的mp3音频,但只播放了第一秒,然后播放器就停止了。我尝试过mp3和wav格式。以下是我的代码:

package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
        mediaPlayer.start();
    }
}
英文:

I'm trying to have MediaPlayer play a roughly two minute long mp3 audio, however only the first second is played then the player stops. I've tired both mp3 and wav formats. Here's my code:

package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MediaPlayer mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
        mediaPlayer.start();
    }
}

</details>


# 答案1
**得分**: 1

你在`onCreate`函数内创建了`MediaPlayer`。因此,在函数返回后,它将被删除。尝试以下代码:

```Java
package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
        mediaPlayer.start();
    }
}
英文:

You create MediaPlayer within the onCreate function. So it will be deleted right after function returns. Try the following code:

package com.pi.audiodemo;
import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = (MediaPlayer) MediaPlayer.create(this, R.raw.dumb);
        mediaPlayer.start();
    }
}

huangapple
  • 本文由 发表于 2020年10月27日 21:31:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64555577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定