gpt4 book ai didi

Android MediaPlayer Streaming YouTube 音频流意外的大声静态

转载 作者:行者123 更新时间:2023-11-29 02:26:46 24 4
gpt4 key购买 nike

我正在尝试的是:
我在远程服务器上的 Python 守护进程中使用 youtube-dl 来获取 URL。
该 URL 被馈送到 Android 应用程序的 MediaPlayer 实例中。

发生了什么:
媒体播放器偶尔会出乎意料地爆炸静电并以正常速度播放,有时它会爆炸静电并以 1.5 倍速度播放。
这是发生了什么的视频。 耳机警告 YouTube Video

观察:
如果有静电,那是整首歌的(不是断断续续的)。
我使用了它提供的 URL,它们在没有静态的 PC 浏览器中运行良好。

它发生在不同的手机上,而且不仅仅是我的手机。
开始轨道需要更长的时间,但轨道最终会变成静态。
静态的轨道使我的进度条(秒分钟显示)表现得很奇怪。我看到它在开始的几秒钟内上下计数,这就是我所说的 1.5 倍速度。

MediaHTTPConnection 引发了很多我不知道如何处理的异常。

E/MediaHTTPConnectionEx: disconnecting
E/MediaHTTPConnectionEx: RuntimeException: Unbalanced enter/exit
mConnection.disconnect();

下面是我的 Python 守护进程返回 URL 的部分

ydl_opts = {
'skip_download':True, # We just want to extract the info
'format':'bestaudio',
'forceurl':True,
'ignoreerrors':True,
'youtube_include_dash_manifest':False,
'restrict_filenames':True,
'source_address':'10.1.0.38',#we have to set this to force ipv4
'logger': MyLogger()
}

def ytdl(self, url):
url2 = "https://www.youtube.com/watch?v="+url
ydl.download([url2])

这是(基本上是样板)MediaPlayer

    public static Stack<Track> tracks = new Stack<>();

private static MediaPlayer mediaPlayer;
private String mediaFile;
private static int duration = 0;

private AudioManager audioManager;
private Boolean userPause = false;

// Binder given to clients
private final IBinder iBinder = new LocalBinder();

public static final String TAG = "Player";

@Override
public IBinder onBind(Intent intent) {
return iBinder;
}

class LocalBinder extends Binder {
Player getService() {
return Player.this;
}
}

public static void seekTo(int msec){
if(mediaPlayer != null){
mediaPlayer.seekTo(msec);
}
}

//The system calls this method when an activity, requests the service be started
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

boolean success = true;

//An audio file is passed to the service through putExtra();
if(intent.hasExtra("uri")){
mediaFile = intent.getStringExtra("uri");
} else {
stopSelf();
success = false;
}
//Request audio focus
if (!requestAudioFocus()) {
//Could not gain focus
Log.d(TAG, "error requesting audio focus");
stopSelf();
success = false;
}

if (mediaFile != null && !mediaFile.equals("") && success) {
Log.d(TAG, "Media File:" + mediaFile);
success = initMediaPlayer();
}
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
//we cant destroy the player here because the back button fires this
//maybe i can not fire super?
super.onDestroy();
/*if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
removeAudioFocus();*/
}

private boolean initMediaPlayer() {

boolean error = false;

//one time setup
if(mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
//setup listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}

//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();

try {
Log.d(TAG, "setDataSource");
mediaPlayer.setDataSource(mediaFile);
} catch (IOException e) {
Log.e(TAG,"setDataSource error:"+e);
error = true;
}

try {
Log.d(TAG, "prepare");
mediaPlayer.prepare();
} catch (IOException e) {
Log.d(TAG, "prepare error");
e.printStackTrace();
error = true;
}
return error;
}


@Override
public void onPrepared(MediaPlayer mp) {
//Invoked when the media source is ready for playback.
Log.d(TAG, "onPrepared");
mp.start();
duration = mp.getDuration();
}

@Override
public void onCompletion(MediaPlayer mp) {
//Invoked when playback of a media source has completed.
removeAudioFocus();
mp.stop();
mp.reset();
}

@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
//Invoked to communicate some info.
return false;
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Invoked indicating buffering status of
//a media resource being streamed over the network.
if(percent%25==0)
Log.d(TAG, "buffering:"+percent);
}

@Override
public void onSeekComplete(MediaPlayer mp) {
//Invoked indicating the completion of a seek operation.
Log.d(TAG, "onSeekComplete() current pos : " + mp.getCurrentPosition());
SystemClock.sleep(200);
start();
}

//Handle errors
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//Invoked when there has been an error during an asynchronous operation
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.e(TAG, "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.e(TAG, "MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.e(TAG, "MEDIA ERROR UNKNOWN " + extra);
//NowPlaying.error = true;
break;
default:
Log.e(TAG, what + "," + extra);
break;
}
PlayerActivity.error = true;
return false;
}

@Override
public void onAudioFocusChange(int focusState) {
//Invoked when the audio focus of the system is updated.
switch (focusState) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
mediaPlayer.setVolume(1.0f, 1.0f);
if(!mediaPlayer.isPlaying()
&& !userPause) {
pause(false);
}
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
removeAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}

private boolean requestAudioFocus() {

int result = 0;
if(audioManager == null) audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
Log.d(TAG, "requestAudioFocus:"+result);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
//Could not gain focus
}

private void removeAudioFocus() {
audioManager.abandonAudioFocus(this);
}

boolean isPlaying() {
if(mediaPlayer != null)
return mediaPlayer.isPlaying();
return false;
}

//pause(true) == pause
//pause(false) == play
//this is used by the system
void pause(Boolean state){
//pause
if (state) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
} else {
if (!mediaPlayer.isPlaying()) {
start();
}
}
}

//this is a pause toggle that is only triggered by the pause/play button
boolean pause() {
if (mediaPlayer.isPlaying()){
userPause = true;
mediaPlayer.pause();
} else {
userPause = false;
start();
}
return !mediaPlayer.isPlaying();
}

void start(){
mediaPlayer.start();
}

int getCurrentPosition(){
if(mediaPlayer != null)
return mediaPlayer.getCurrentPosition();
return 0;
}

int getDuration(){
return duration;
}
}

最佳答案

我觉得其他人也会遇到这个问题,所以我要发布我的解决方案。

所以我注意到每首轨道都会弹出一个 mime 类型错误。现在我已经解决了这个问题,但仍然出现错误,但是响亮的静电声已经停止。

这是启动轮子转动的错误:

E/MediaHTTPConnectionEx: getMIMEType
[seekToEx] offset:0/mCurrentOffset:-1


我注意到 youtube-dl 为 webm 提供的一些 URL 没有在 URL 中指定 mime 类型。

这是一个例子:

...O8c2&mime=&pl=...

但是所有的 m4a 流在 URL 中都有一个 mime 类型

...70F61&mime=audio%2Fmp4&itag=140&key...

所以我认为虽然我的解决方案不是最好的解决方案,但它是最简单的。由于所有 m4a 流都指定了一个 mime,所以我只限于那些流。

难点在于:
我非常确定,如果我只是检查指定 MIME 字段的 URL,我仍然可以播放大多数 webm 文件。唯一失败的(静态)是没有该字段的 URL。

我的解决方案:

Python 只提取 m4a 文件:

...
'format':'bestaudio[ext=m4a]',
...

Android 现在传递硬编码 header :

Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "audio/mp4"); // change content type if necessary
Uri uri = Uri.parse(mediaFile);
Log.d(TAG, "getMimeType="+getMimeType(uri));//this is ALWAYS null
mediaPlayer.setDataSource(getApplicationContext(), uri, headers);

关于Android MediaPlayer Streaming YouTube 音频流意外的大声静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51832505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com