4
4

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 5 years have passed since last update.

iOS Audioタグで曲の長さが取得できない問題

Last updated at Posted at 2017-02-11

はじめに

音声配信サービスを開発中でHTML5で追加されたAudioタグを使ってプレイヤーの実装を行っていたが一部で曲の長さが取得できない問題に遭遇した。

曲の長さの取得方法

コピペしても動かないけど、曲の長さの取得方法はこんな感じ。

index.html
<!doctype html>
<html>
<body>
  <audio id="audio" src="sample.mp3"></audio>
</body>
</html>
app.js
var $audio = document.getElementById("audio");
$audio.addEventListener("loadedmetadata", function() {
  console.log( $audio.duration );
});

こんな感じのコードを実行する。
メタデータが取得できる状態になるとイベントが発火、コンソールに曲の長さが表示される。

問題

最新のiOSを含めたiOSでdurationが上手く取得できずinfinityが返ってくる。
しかも、ある環境では問題なく取得できて、ある環境では取得できない。
取得できない環境でも、1度最後まで再生すると取得できる。

原因

サーバーのレスポンスがContent-Rangeに対応していない。
Content-Rangeの詳しいことはRFC読んでください。
RFC 7233 — HTTP/1.1: Range Requests (日本語訳

解決法

クライアントではどうしようもないのでサーバー側でContent-Rangeに対応する。

注意

この問題すべての解決法がこの原因かはわからないという事です。

あとがき

曲の長さが取得できない場合があるという記事は多く見かけましたが、Content-Rangeに対応していないからという記事が日本語では見つからなかったので書いてみました。
何か他の情報をお持ちの方はぜひコメントなどいただけると幸いです。

ちなみに、Content-Rangeに対応していなくて手持ちのAndroid、およびPCブラウザでは曲の長さが取得できていたのでiOS固有の問題っぽいです。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?