在Flutter中播放自定义声音 [英] Play a Custom Sound in Flutter

查看:769
本文介绍了在Flutter中播放自定义声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试播放自定义mp3声音,就像将字体或图像文件放置在app文件夹中一样,已将其放置在app文件夹中,但是后来我真的不知道该如何进行.我想可能需要将音频文件注册到pubspec.yaml中,但是如何?

I'm trying to Play a custom mp3 sound I've put in an asset folder into the app folder, like you would do for a font or an image file, but then I don't really know how to proceed. I think I might need to register the audio file into the pubspec.yaml, but how?

那我怎么玩呢?

我已经检查了以下两个答案: 如何在Flutter中播放自定义声音?

I've checked out this two answer: How to play a custom sound in Flutter?

Flutter-播放自定义声音是否已更新?

但是第一个太旧了,第二个使用URL作为声音路径:const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3";,我想播放的声音在应用程序中,而不是在线.所以...我该怎么办?

But the first one is too old and the second one uses URLs as the sound path: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3"; and the sound I like to play is in the app, not online. So... How can I do it?

这是我当前的代码,如您所见,只有一个浮动按钮. 而且我需要从代码中指出的那一点开始声音.

This Is My Current Code, as You can see, there's only a Floating Button. And I need To Start The Sound at the Point I stated it in the code.

但是Visual Studio以红色突出显示各个部分: await :表示无法识别await. audioPlugin.play :是说它也无法识别

But visual studio underlines in red Various Parts: await: it says that await is unrecognized. audioPlugin.play: is says It's also unrecognized

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),
      ),
    );
  }
}

推荐答案

虽然不漂亮,但是...

It's not pretty, but...

将mp3文件添加到资产文件夹,然后将其添加到pubspec.yaml,例如.

Add the mp3 file to the assets folder and add it to pubspec.yaml like this.

使用rootBundle.load(asset)

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

Use path_provider to get the app's temp folder location

使用常规的dart:iotempDir中打开文件(也许使用资产名称)并向其中写入bytes.

Use regular dart:io to open a file in tempDir (maybe use the asset name) and write bytes to it.

从临时文件名中以file:///folderPath/fileName

将此内容传递给音频播放器,将isLocal设置为true(iOS上需要).

Pass this to audioplayer, setting isLocal to true (needed on 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),
      ),
    );
  }
}

这篇关于在Flutter中播放自定义声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆