Cant get mediaplayer sound on Android 9,10 Xamarin

2020-04-17 04:02发布

问题:

Im using this code on the android 8 and below but on Android version 9+ its not working.

MediaPlayer player3;
        player3 = new MediaPlayer();
        player3.SetDataSource(url);
        player3.SetAudioStreamType(Stream.Music);
        player3.Completion += mediaPlayer_Completion;
        player3.PrepareAsync();
        player3.Start();

EDIT: Im trying to reproduce a audio stream link. The player doesn't do anything. The same code it works fine on another android versions.

回答1:

After Android 9 (API level 28), cleartext support is disabled by default.

Check https://koz.io/android-m-and-the-war-on-cleartext-traffic/

Solution 1

Create file network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">Your video URL(ex: 127.0.0.1)</domain>
    </domain-config>
</network-security-config>

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>

Solution 2

Android:usesCleartextTraffic Doc

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>