在后台运行的应用程序(即 Google Play 音乐、Apple Music、Spotify 等)上播放音乐时,如果您在 flutter 应用程序中播放任何音频,背景音乐只会停止/暂停,并且在音频播放完成后不会重新启动玩。
我已经在 iOS 上使用 TTS 库和 AudioPlayer 库尝试过这个。
关于如何在我的音频完成后继续播放背景音频(实际上只是 2/3 秒的短语)的任何提示?
尚不确定这是否会影响 Android。
注意:本示例中使用了 TTS,但它发生在我尝试过的每个库中。
pubspec.yaml
tts: "^1.0.1"
Run Code Online (Sandbox Code Playgroud)
代码:
import 'package:flutter/material.dart';
import 'package:tts/tts.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: AudioExample(),
);
}
}
class AudioExample extends StatefulWidget {
@override
_AudioExampleState createState() => _AudioExampleState();
}
class _AudioExampleState extends State<AudioExample> {
speak() async {
Tts.speak('Hello World');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Audio example app'),
),
body: Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
color: Colors.grey[300],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.play_arrow),
onPressed: speak,
color: Colors.red,
iconSize: 100.0,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
'Will say hello world once clicked and pause background audio on iOS - how to restart background audio after playing has finished?',
textAlign: TextAlign.center,
),
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 -1
您可以比 Flutter 更好地在 Java 文件中添加音乐并添加循环转到 android/app/src/main/java/com/example/ProjectName/MainActivity.java
并添加
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.MusicName);
mediaPlayer.setLooping(true);
mediaPlayer.start();
mediaPlayer.setLooping(true);
Run Code Online (Sandbox Code Playgroud)
在 onCreate 方法中,转到名为 res 的文件夹,并在其中创建一个名为 raw 的文件夹,然后将您的音乐放入其中
归档时间: |
|
查看次数: |
3770 次 |
最近记录: |