Unlock the Power of Audio in Your Flutter App

Getting Started

Before we dive in, ensure you have the following:

  • Flutter installed
  • Android Studio or Xcode installed
  • A new Flutter app created with the command flutter create my_app

Setting Up the App

Open your newly created Flutter app in your preferred code editor and navigate to main.dart. Remove the debug mode banner by setting debugShowCheckedModeBanner to false. All our code will be inside the MyHomePageState class.

Designing the UI

Let’s add a timer feature to our app, which will display the recording time. Create a Container widget with a Text widget as its child, and style the timer text using TextStyle. We’ll create a function to pass the timer into the _timerText variable later.


Container(
  child: Text(
    _timerText,
    style: TextStyle(fontSize: 24),
  ),
)

Next, let’s create two buttons to start and stop recording. Use a Row widget to place the buttons on the same row, and utilize Flutter’s ElevatedButton widget to create the buttons. Each button will have its own unique icon, text, and color.


Row(
  children: [
    ElevatedButton(
      icon: Icon(Icons.play_arrow),
      onPressed: _startRecording,
      child: Text('Start Recording'),
      style: ElevatedButton.styleFrom(primary: Colors.green),
    ),
    ElevatedButton(
      icon: Icon(Icons.stop),
      onPressed: _stopRecording,
      child: Text('Stop Recording'),
      style: ElevatedButton.styleFrom(primary: Colors.red),
    ),
  ],
)

Recording Audio

Create a function to start recording, which will initialize the app, open an audio session, and start recording. We’ll use the FlutterSoundRecorder package to achieve this.


void _startRecording() async {
  final directory = await getApplicationDocumentsDirectory();
  final filePath = directory.path + '/audio.aac';
  
  if (!await directory.exists()) {
    await directory.create();
  }
  
  await openAudioSession();
  await _recorder.startRecorder(toFile: filePath);
  
  _recordingSession.onProgress.listen((event) {
    setState(() {
      _timerText = event.duration.toString();
    });
  });
}

Playing Audio

Create a function to play the recorded audio, which will use the assets_audio_player package.


void _play() async {
  final filePath = 'assets/recorded_audio.aac';
  await AudioPlayer().open(filePath, autoStart: true);
}

Stopping Audio

Create a function to stop the audio playback, which will use the stop method to stop the player.


void _stop() async {
  await AudioPlayer().stop();
}

Finalizing the App

With these functions in place, we’ve successfully added audio recording and playback features to our Flutter app.

Additional Resources

Here are the final code snippets for the main.dart, AndroidManifest.xml, and pubspec.yaml files:


// main.dart file
// [insert code]

// AndroidManifest.xml file
// [insert code]

// pubspec.yaml file
// [insert code]

Leave a Reply