颤振音频播放器播放声音无法在IOS中运行

时间:2018-10-14 07:55:31

标签: ios flutter audio-player

我使用的是Flutter插件audioplayers: ^0.7.8,,以下代码在Android中有效,但在IOS中无效。我在真正的ios设备中运行代码,然后单击按钮。它假定正在播放mp3文件,但完全没有声音。请帮助解决此问题。

我已经设置了info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

在这里从控制台打印出来:

  • 颤振:完成加载,uri =文件:///var/mobile/Containers/Data/Application/E3A576E2-0F21-44CF-AF99-319D539767D0/Library/Caches/demo.mp3
  • 正在将文件同步到设备iPhone ...
  • 颤振:_platformCallHandler调用audio.onCurrentPosition {playerId:273e1d27-b6e8-4516-bb3f-967a41dff308,值:0}
  • 颤振:_platformCallHandler调用audio.onError {playerId:273e1d27-b6e8-4516-bb3f-967a41dff308,值:AVPlayerItemStatus.failed}

以下是我的代码:

class _MyHomePageState extends State<MyHomePage> {
  AudioPlayer audioPlugin = AudioPlayer();
  String mp3Uri;

  @override
  void initState() {
    AudioPlayer.logEnabled = true;
    _load();
  }

  Future<Null> _load() async {
    final ByteData data = await rootBundle.load('assets/demo.mp3');
    Directory tempDir = await getTemporaryDirectory();
    File tempFile = File('${tempDir.path}/demo.mp3');
    await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
    mp3Uri = tempFile.uri.toString();
    print('finished loading, uri=$mp3Uri');
  }

  void _playSound() {
    if (mp3Uri != null) {
      audioPlugin.play(mp3Uri, isLocal: true,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Audio Player Demo Home Page'),
      ),
      body: Center(),
      floatingActionButton: FloatingActionButton(
        onPressed: _playSound,
        tooltip: 'Play',
        child: const Icon(Icons.play_arrow),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:2)

如果要使用本地文件,则必须使用AudioCache

看文档,它在底部说:

AudioCache

  

要播放本地资产,必须使用AudioCache类。

  Flutter无法提供一种轻松播放资产音频的简便方法,但是此类对您有很大帮助。它实际上将资产复制到设备中的临时文件夹中,然后在其中作为本地文件播放。

它用作缓存,因为它会跟踪复制的文件,以便您可以随后进行回放刻不容缓。

要播放音频,这是我想出的方法:

import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';

AudioCache audioPlayer = AudioCache();

void main() {
  runApp(new MyApp());
}




class MyApp extends StatefulWidget {
  @override _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override initState(){
    super.initState();
    audioPlayer.play("Jingle_Bells.mp3");
  }
  @override Widget build(BuildContext context) {
    //This we do not care about
  }
}

重要提示:

它会自动在路径前面放置“资产/”。这意味着您如果要加载assets/Jingle_Bells.mp3,只需放入audioPlayer.play("Jingle_Bells.mp3");。如果您改为输入audioPlayer.play("assets/Jingle_Bells.mp3");,则AudioPlayers实际上将加载assets/assets/Jingle_Bells.mp3

``