joaopaulofcc

Untitled

Oct 29th, 2020
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 6.24 KB | None | 0 0
  1. // Importa bibliotecas
  2. import 'package:file_picker/file_picker.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:audioplayers/audioplayers.dart';
  5.  
  6. void main() => runApp(MyApp());
  7.  
  8. class MyApp extends StatelessWidget {
  9.   @override
  10.   Widget build(BuildContext context) {
  11.     return MaterialApp(
  12.       title: 'AudioPlayer',
  13.       theme: ThemeData(
  14.         primarySwatch: Colors.blue,
  15.       ),
  16.       home: MyHomePage(title: 'Audio Player'),
  17.     );
  18.   }
  19. }
  20.  
  21. class MyHomePage extends StatefulWidget {
  22.   MyHomePage({Key key, this.title}) : super(key: key);
  23.   final String title;
  24.   @override
  25.   _MyHomePageState createState() => _MyHomePageState();
  26. }
  27.  
  28. class _MyHomePageState extends State<MyHomePage> {
  29.   // Variável que armazena true se algo está sendo executado.
  30.   bool _isPlaying = false;
  31.  
  32.   // Criar um objeto da classe AudioPlayer.
  33.   AudioPlayer audioPlayer;
  34.  
  35.   @override
  36.   void initState() {
  37.     super.initState();
  38.     audioPlayer = AudioPlayer();
  39.   }
  40.  
  41.   // Método responsável por executar um arquivo remoto.
  42.   playAudioFromURL(path) async {
  43.     // Chama função play informando o caminho do arquivo e que ele não é local.
  44.     int response = await audioPlayer.play(path, isLocal: false);
  45.  
  46.     // Verifica se ocorreu algum erro ao executar.
  47.     if (response == 1) {
  48.       setState(() {
  49.         _isPlaying = true;
  50.       });
  51.     } else {
  52.       print('Algum erro ocorreu ao executar o arquivo remoto!');
  53.     }
  54.   }
  55.  
  56.   // Método responsável por executar um arquivo local.
  57.   playAudioFromLocalStorage(path) async {
  58.     // Chama função play informando o caminho do arquivo e que ele é local.
  59.     int response = await audioPlayer.play(path, isLocal: true);
  60.  
  61.     // Verifica se ocorreu algum erro ao executar.
  62.     if (response == 1) {
  63.       setState(() {
  64.         _isPlaying = true;
  65.       });
  66.     } else {
  67.       print('Algum erro ocorreu ao executar o arquivo local!');
  68.     }
  69.   }
  70.  
  71.   // Função que pausa a execução.
  72.   pauseAudio() async {
  73.     // Chama método pause.
  74.     int response = await audioPlayer.pause();
  75.  
  76.     // Verifica se ocorreu algum erro ao pausar.
  77.     if (response == 1) {
  78.       setState(() {
  79.         _isPlaying = false;
  80.       });
  81.     } else {
  82.       print('Algum erro ocorreu ao pausar!');
  83.     }
  84.   }
  85.  
  86.   // Método que para a execução do arquivo.
  87.   stopAudio() async {
  88.     // Chama método stop.
  89.     int response = await audioPlayer.stop();
  90.  
  91.     // Verifica se ocorreu algum erro ao parar.
  92.     if (response == 1) {
  93.       setState(() {
  94.         _isPlaying = false;
  95.       });
  96.     } else {
  97.       print('Algum erro ocorreu ao parar!');
  98.     }
  99.   }
  100.  
  101.   // Método que é responsável por continuar a execução do áudio (após pause).
  102.   resumeAudio() async {
  103.     // Chama método resume.
  104.     int response = await audioPlayer.resume();
  105.  
  106.     // Verifica se ocorreu algum erro ao executar.
  107.     if (response == 1) {
  108.       setState(() {
  109.         _isPlaying = true;
  110.       });
  111.     } else {
  112.       print('Algum erro ocorreu ao continuar!');
  113.     }
  114.   }
  115.  
  116.   // Constroi interface.
  117.   @override
  118.   Widget build(BuildContext context) {
  119.     return Scaffold(
  120.       appBar: AppBar(
  121.         title: Text(widget.title),
  122.       ),
  123.       body: Center(
  124.         child: Column(
  125.           mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  126.           children: [
  127.             Container(
  128.               child: Column(
  129.                 children: [
  130.                   Row(
  131.                     mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  132.                     children: [
  133.                       // Botão play//pause
  134.                       RaisedButton(
  135.                         onPressed: () {
  136.                           // Se estiver executando, atua como pause.
  137.                           if (_isPlaying == true) {
  138.                             pauseAudio();
  139.                           }
  140.                           // Se não estiver executando atua como resume.
  141.                           else {
  142.                             resumeAudio();
  143.                           }
  144.                         },
  145.                         // De acordo com a situação, mostra o ícone adequado.
  146.                         child:
  147.                             Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
  148.                         color: Colors.blue,
  149.                       ),
  150.  
  151.                       // Botão de stop.
  152.                       RaisedButton(
  153.                         onPressed: () {
  154.                           stopAudio();
  155.                         },
  156.                         child: Icon(Icons.stop),
  157.                         color: Colors.blue,
  158.                       ),
  159.                     ],
  160.                   ),
  161.                 ],
  162.               ),
  163.             ),
  164.             Row(
  165.               mainAxisAlignment: MainAxisAlignment.spaceAround,
  166.               children: [
  167.                 // Botão que chama o explorador de arquivos, para o usuário
  168.                 // selecionar o arquivo que será exibido.
  169.                 RaisedButton(
  170.                   onPressed: () async {
  171.                     var path =
  172.                         await FilePicker.getFilePath(type: FileType.audio);
  173.  
  174.                     // ao escolher o arquivo, imediatamente o executa.
  175.                     setState(() {
  176.                       _isPlaying = true;
  177.                     });
  178.                     playAudioFromLocalStorage(path);
  179.                   },
  180.                   child: Text(
  181.                     'Arquivo local',
  182.                     style: TextStyle(color: Colors.white),
  183.                   ),
  184.                   color: Colors.blueAccent,
  185.                 ),
  186.                 RaisedButton(
  187.                   onPressed: () async {
  188.                     // Endereço remoto do arquivo.
  189.                     var path =
  190.                         "https://www.giampaolonoto.it/samplebank/THEWALL-Helicopterwithvocals.mp3";
  191.  
  192.                     // Chama método para executar o arquivo remoto.
  193.                     playAudioFromURL(path);
  194.                   },
  195.                   child: Text(
  196.                     'Arquivo remoto',
  197.                     style: TextStyle(color: Colors.white),
  198.                   ),
  199.                   color: Colors.blueAccent,
  200.                 ),
  201.               ],
  202.             ),
  203.           ],
  204.         ),
  205.       ),
  206.     );
  207.   }
  208. }
  209.  
Add Comment
Please, Sign In to add comment