Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Importa bibliotecas
- import 'package:file_picker/file_picker.dart';
- import 'package:flutter/material.dart';
- import 'package:audioplayers/audioplayers.dart';
- void main() => runApp(MyApp());
- class MyApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- title: 'AudioPlayer',
- theme: ThemeData(
- primarySwatch: Colors.blue,
- ),
- home: MyHomePage(title: 'Audio Player'),
- );
- }
- }
- class MyHomePage extends StatefulWidget {
- MyHomePage({Key key, this.title}) : super(key: key);
- final String title;
- @override
- _MyHomePageState createState() => _MyHomePageState();
- }
- class _MyHomePageState extends State<MyHomePage> {
- // Variável que armazena true se algo está sendo executado.
- bool _isPlaying = false;
- // Criar um objeto da classe AudioPlayer.
- AudioPlayer audioPlayer;
- @override
- void initState() {
- super.initState();
- audioPlayer = AudioPlayer();
- }
- // Método responsável por executar um arquivo remoto.
- playAudioFromURL(path) async {
- // Chama função play informando o caminho do arquivo e que ele não é local.
- int response = await audioPlayer.play(path, isLocal: false);
- // Verifica se ocorreu algum erro ao executar.
- if (response == 1) {
- setState(() {
- _isPlaying = true;
- });
- } else {
- print('Algum erro ocorreu ao executar o arquivo remoto!');
- }
- }
- // Método responsável por executar um arquivo local.
- playAudioFromLocalStorage(path) async {
- // Chama função play informando o caminho do arquivo e que ele é local.
- int response = await audioPlayer.play(path, isLocal: true);
- // Verifica se ocorreu algum erro ao executar.
- if (response == 1) {
- setState(() {
- _isPlaying = true;
- });
- } else {
- print('Algum erro ocorreu ao executar o arquivo local!');
- }
- }
- // Função que pausa a execução.
- pauseAudio() async {
- // Chama método pause.
- int response = await audioPlayer.pause();
- // Verifica se ocorreu algum erro ao pausar.
- if (response == 1) {
- setState(() {
- _isPlaying = false;
- });
- } else {
- print('Algum erro ocorreu ao pausar!');
- }
- }
- // Método que para a execução do arquivo.
- stopAudio() async {
- // Chama método stop.
- int response = await audioPlayer.stop();
- // Verifica se ocorreu algum erro ao parar.
- if (response == 1) {
- setState(() {
- _isPlaying = false;
- });
- } else {
- print('Algum erro ocorreu ao parar!');
- }
- }
- // Método que é responsável por continuar a execução do áudio (após pause).
- resumeAudio() async {
- // Chama método resume.
- int response = await audioPlayer.resume();
- // Verifica se ocorreu algum erro ao executar.
- if (response == 1) {
- setState(() {
- _isPlaying = true;
- });
- } else {
- print('Algum erro ocorreu ao continuar!');
- }
- }
- // Constroi interface.
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text(widget.title),
- ),
- body: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.spaceEvenly,
- children: [
- Container(
- child: Column(
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceEvenly,
- children: [
- // Botão play//pause
- RaisedButton(
- onPressed: () {
- // Se estiver executando, atua como pause.
- if (_isPlaying == true) {
- pauseAudio();
- }
- // Se não estiver executando atua como resume.
- else {
- resumeAudio();
- }
- },
- // De acordo com a situação, mostra o ícone adequado.
- child:
- Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
- color: Colors.blue,
- ),
- // Botão de stop.
- RaisedButton(
- onPressed: () {
- stopAudio();
- },
- child: Icon(Icons.stop),
- color: Colors.blue,
- ),
- ],
- ),
- ],
- ),
- ),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceAround,
- children: [
- // Botão que chama o explorador de arquivos, para o usuário
- // selecionar o arquivo que será exibido.
- RaisedButton(
- onPressed: () async {
- var path =
- await FilePicker.getFilePath(type: FileType.audio);
- // ao escolher o arquivo, imediatamente o executa.
- setState(() {
- _isPlaying = true;
- });
- playAudioFromLocalStorage(path);
- },
- child: Text(
- 'Arquivo local',
- style: TextStyle(color: Colors.white),
- ),
- color: Colors.blueAccent,
- ),
- RaisedButton(
- onPressed: () async {
- // Endereço remoto do arquivo.
- var path =
- "https://www.giampaolonoto.it/samplebank/THEWALL-Helicopterwithvocals.mp3";
- // Chama método para executar o arquivo remoto.
- playAudioFromURL(path);
- },
- child: Text(
- 'Arquivo remoto',
- style: TextStyle(color: Colors.white),
- ),
- color: Colors.blueAccent,
- ),
- ],
- ),
- ],
- ),
- ),
- );
- }
- }
Add Comment
Please, Sign In to add comment