首页 文章

在Flutter中播放自定义声音

提问于
浏览
0

我正在尝试播放一个自定义的mp3声音我已经将资产文件夹放入app文件夹中,就像你对字体或图像文件所做的那样,但后来我真的不知道如何继续 . 我想我可能需要将音频文件注册到pubspec.yaml,但是如何?

我该怎么玩呢?

我已经检查了这两个答案:How to play a custom sound in Flutter?

Flutter - Play custom sounds updated?

但是第一个太旧了,第二个使用URL作为声音路径: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3"; 而我喜欢播放的声音是在应用中,而不是在线 . 那么......我怎么能这样做?

这是我的当前代码,如您所见,只有一个浮动按钮 . 我需要在点上启动声音我在代码中说明了它 .

但是视觉工作室以红色突出显示各个部分: await :它表示等待无法识别 . audioPlugin.play :是说它也未被承认

import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());

Directory tempDir = await getTemporaryDirectory();
File tempFile = new File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(bytes, flush: true);
AudioPlayer audioPlugin = new AudioPlayer();


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  void _incrementCounter() {
    setState(() {
      print("Button Pressed");

      ///
      /// 
      /// 
      /// Here I Need To start Playing the Sound
      /// 
      /// 
      /// 
      /// 
      audioPlugin.play(tempFile.uri.toString(), isLocal: true);

    });
  }



  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

1 回答

  • 0

    它不漂亮,但......

    将mp3文件添加到assets文件夹并将其添加到 pubspec.yaml ,如this .

    使用 rootBundle.load(asset) 将资产作为二进制数据加载

    使用 path_provider 获取应用程序的临时文件夹位置

    使用常规 dart:iotempDir 中打开文件(可能使用资产名称)并将 bytes 写入其中 .

    file:///folderPath/fileName 形式的临时文件名形成 file URL

    将此传递给audioplayer,将 isLocal 设置为true(在iOS上需要) .

    import 'dart:async';
    import 'dart:io';
    import 'dart:typed_data';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:audioplayer/audioplayer.dart';
    import 'package:path_provider/path_provider.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Audio Player Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key key}) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      AudioPlayer audioPlugin = AudioPlayer();
      String mp3Uri;
    
      @override
      void initState() {
        _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),
          ),
        );
      }
    }
    

相关问题