Skip to content

Commit

Permalink
update return type of result when user stop the audio player
Browse files Browse the repository at this point in the history
  • Loading branch information
himanshuGandhiSimform committed Nov 26, 2024
1 parent 7b97514 commit 06e27ca
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,43 +66,43 @@ class AudioRecorder : PluginRegistry.RequestPermissionsResultListener {

fun stopRecording(result: MethodChannel.Result, recorder: MediaRecorder?, path: String) {
try {
val audioInfoArrayList = ArrayList<String?>()

val hashMap : HashMap<String,Any?> = HashMap()
try {
recorder?.stop()

val duration = getDuration(path)
audioInfoArrayList.add(path)
audioInfoArrayList.add(duration)

hashMap[Constants.resultFilePath] = path
hashMap[Constants.resultDuration] = duration
} catch (e: RuntimeException) {
// Stop was called immediately after start which causes stop() call to fail.
audioInfoArrayList.add(null)
audioInfoArrayList.add("-1")
hashMap[Constants.resultFilePath] = null
hashMap[Constants.resultDuration] = "-1"
}

recorder?.apply {
reset()
release()
}

result.success(audioInfoArrayList)
result.success(hashMap)
} catch (e: IllegalStateException) {
Log.e(LOG_TAG, "Failed to stop recording")
}
}

private fun getDuration(path: String): String {
private fun getDuration(path: String): Int {
val mediaMetadataRetriever = MediaMetadataRetriever()
try {
mediaMetadataRetriever.setDataSource(path)
val duration = mediaMetadataRetriever.extractMetadata(METADATA_KEY_DURATION)
return duration ?: "-1"
return duration?.toInt() ?: -1
} catch (e: Exception) {
Log.e(LOG_TAG, "Failed to get recording duration")
} finally {
mediaMetadataRetriever.release()
}
return "-1"
return -1
}

fun startRecorder(result: MethodChannel.Result, recorder: MediaRecorder?, useLegacy: Boolean) {
Expand Down
3 changes: 3 additions & 0 deletions android/src/main/kotlin/com/simform/audio_waveforms/Utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ object Constants {
const val waveformData = "waveformData"
const val useLegacyNormalization = "useLegacyNormalization"
const val updateFrequency = "updateFrequency"

const val resultFilePath = "resultFilePath"
const val resultDuration = "resultDuration"
}

enum class FinishMode(val value:Int) {
Expand Down
16 changes: 12 additions & 4 deletions ios/Classes/AudioRecorder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,26 +62,34 @@ public class AudioRecorder: NSObject, AVAudioRecorderDelegate{
audioRecorder?.stop()
if(audioUrl != nil) {
let asset = AVURLAsset(url: audioUrl!)

if #available(iOS 15.0, *) {
Task {
do {
recordedDuration = try await asset.load(.duration)
result([path,Int(recordedDuration.seconds * 1000).description])
sendResult(result, duration: Int(recordedDuration.seconds * 1000))
} catch let err {
debugPrint(err.localizedDescription)
result([path,CMTime.zero.seconds.description])
sendResult(result, duration: Int(CMTime.zero.seconds))
}
}
} else {
recordedDuration = asset.duration
result([path,Int(recordedDuration.seconds * 1000).description])
sendResult(result, duration: Int(recordedDuration.seconds * 1000))
}
} else {
result([path,CMTime.zero.seconds.description])
sendResult(result, duration: Int(CMTime.zero.seconds))
}
audioRecorder = nil
}

private func sendResult(_ result: @escaping FlutterResult, duration:Int){
var params = [String:Any?]()
params[Constants.resultFilePath] = path
params[Constants.resultDuration] = duration
result(params)
}

public func pauseRecording(_ result: @escaping FlutterResult) {
audioRecorder?.pause()
result(false)
Expand Down
2 changes: 2 additions & 0 deletions ios/Classes/Utils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ struct Constants {
static let useLegacyNormalization = "useLegacyNormalization"
static let updateFrequency = "updateFrequency"
static let overrideAudioSession = "overrideAudioSession"
static let resultFilePath = "resultFilePath"
static let resultDuration = "resultDuration"
}

enum FinishMode : Int{
Expand Down
6 changes: 3 additions & 3 deletions lib/src/base/audio_waveforms_interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ class AudioWaveformsInterface {
}

///platform call to stop recording
Future<List<String?>?> stop() async {
final audioInfo =
Future<Map<String, dynamic>> stop() async {
Map<Object?, Object?> audioInfo =
await _methodChannel.invokeMethod(Constants.stopRecording);
return List.from(audioInfo ?? []);
return audioInfo.cast<String, dynamic>();
}

///platform call to resume recording.
Expand Down
2 changes: 2 additions & 0 deletions lib/src/base/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,6 @@ class Constants {
static const String useLegacyNormalization = "useLegacyNormalization";
static const String updateFrequency = "updateFrequency";
static const String overrideAudioSession = "overrideAudioSession";
static const String resultFilePath = "resultFilePath";
static const String resultDuration = "resultDuration";
}
30 changes: 13 additions & 17 deletions lib/src/controllers/recorder_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:io' show Platform;
import 'dart:math' show max;

import 'package:audio_waveforms/src/base/constants.dart';
import 'package:flutter/material.dart';

import '/src/base/utils.dart';
Expand Down Expand Up @@ -310,24 +311,19 @@ class RecorderController extends ChangeNotifier {
Future<String?> stop([bool callReset = true]) async {
if (_recorderState.isRecording || _recorderState.isPaused) {
final audioInfo = await AudioWaveformsInterface.instance.stop();
if (audioInfo != null) {
_isRecording = false;
_timer?.cancel();
_recorderTimer?.cancel();
if (audioInfo[1] != null) {
var duration = int.tryParse(audioInfo[1]!);
if (duration != null) {
_recordedDuration = Duration(milliseconds: duration);
_recordedFileDurationController.add(recordedDuration);
}
}
_elapsedDuration = Duration.zero;
_setRecorderState(RecorderState.stopped);
if (callReset) reset();
return audioInfo[0];
} else {
throw "Failed stop recording";
_isRecording = false;
_timer?.cancel();
_recorderTimer?.cancel();
if (audioInfo[Constants.resultDuration] != null) {
var duration = audioInfo[Constants.resultDuration];

_recordedDuration = Duration(milliseconds: duration);
_recordedFileDurationController.add(recordedDuration);
}
_elapsedDuration = Duration.zero;
_setRecorderState(RecorderState.stopped);
if (callReset) reset();
return audioInfo[Constants.resultFilePath];
}

notifyListeners();
Expand Down

0 comments on commit 06e27ca

Please sign in to comment.