0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Android】MediaPlayerでURLから再生するときの設定方法

Posted at

プログラミング勉強日記

2021年1月15日
昨日の記事でMediaPlayerで音楽を再生する方法について簡単に記述したが、URLから再生する場合には、マニフェストの宣言が必要なので、これも記事として残しておく。

URLから音楽を再生する

MainActivity.java
String url = "http://........";
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(url);
mp.prepare(); 
mp.start();

マニフェストの宣言

 MediaPlayerを使用してネットワークの音楽を再生する場合には、ネットワークアクセスを許可する必要がある。

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

ただ、私の場合はこれだけではURLから再生することができなかった。これに加えて、アプリネットワーク設定を用意した。

ネットワークセキュリティの構成

 ネットワークセキュリティ構成機能はxmlファイルを使用する。まず、アプリのマニュアルにこのxmlファイルを指すエントリを含める。

AndroidManifest.xml
    <manifest ... >
        <application android:networkSecurityConfig="@xml/network_security_config"
                        ... >
            ...
        </application>
    </manifest>

 次に構成ファイルを作成する。

image.png

 
 Android 6.0(API レベル 23)以下を対象とするアプリのデフォルトの構成は以下のようになる。

network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>

 ここまで設定して、やっとURLから音楽を再生することができた。(詳しくはAndroid developersのネットワーク セキュリティ構成に書かれている。)

参考文献

MediaPlayer の概要
ネットワーク セキュリティ構成

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?