Flutter Play Sound and Record Noise Levels

1.9k views Asked by At

Can anybody help plz!

Ive been running into this issue for a while now. The app runs fine on an ios simulator aswell as android device but not on an ios device. The general idea is that i want a tone to play and once that tone starts playing i need to record the decibel levels that the device picks up. From what i understand, the ios device only allows for one channel to be used at a time, wheather it be input or output. I am using the audioplayers and noise_meter plugins. All permissions have been granted and if i run the one method alone it works and visa versa but when running both methods it throws this error.

https://pub.dev/packages/noise_meter

https://pub.dev/packages/audioplayers

The errors i am receiving are below:

"iOS => call startHeadlessService, playerId fa642ed8-2266-48b6-ac9f-1f474f225864"
"calling start headless service (\n    4430477584143042153\n)"
"iOS => call setReleaseMode, playerId fa642ed8-2266-48b6-ac9f-1f474f225864"
"iOS => call play, playerId fa642ed8-2266-48b6-ac9f-1f474f225864"
"setUrl /var/mobile/Containers/Data/Application/0E0D63C7-B1DD-4BD3-BC84-2AFB5C80B8D9/Library/Caches/2100.mp3"
[VERBOSE-2:FlutterObservatoryPublisher.mm(101)] Failed to register observatory port with mDNS with error -65555.
[VERBOSE-2:FlutterObservatoryPublisher.mm(103)] On iOS 14+, local network broadcast in apps need to be declared in the app's Info.plist. Debug and profile Flutter apps and modules host VM services on the local network to support debugging features such as hot reload and DevTools. To make your Flutter app or module attachable and debuggable, add a '_dartobservatory._tcp' value to the 'NSBonjourServices' key in your Info.plist for the Debug/Profile configurations. For more information, see https://flutter.dev/docs/development/add-to-app/ios/project-setup#local-network-privacy-permissions
""
"iOS -> updateDuration...1.541224"
"iOS -> invokechannel"
"iOS -> onSoundComplete..."
[avas]     AVAudioSession_iOS.mm:1149  Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.
"Error inactivating audio session Error Domain=NSOSStatusErrorDomain Code=560030580 \"(null)\""

Ive put a simple application together to merely demonstrate my issue:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/services.dart';
import 'package:noise_meter/noise_meter.dart';


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);



  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static AudioCache player = AudioCache();

  bool _isRecording = false;
  StreamSubscription<NoiseReading> _noiseSubscription;
  NoiseMeter _noiseMeter;

  playSound() async{
    player.play("2100.mp3");
  }


  void start() async {
    //_noiseSubscription = _noiseMeter.noiseStream.listen(onData);

    try {
      _noiseSubscription = _noiseMeter.noiseStream.listen(onData);
    } catch (exception) {
      print(exception);
    }
  }

  void onData(NoiseReading noiseReading) {
    this.setState(() {
      if (!this._isRecording) {
        this._isRecording = true;
      }
    });
    /// Do someting with the noiseReading object
    print(noiseReading.toString());
  }

  void onError(PlatformException e) {
    print(e.toString());
    _isRecording = false;
  }

  void stopRecorder() async {
    try {
      if (_noiseSubscription != null) {
        _noiseSubscription.cancel();
        _noiseSubscription = null;
      }
      this.setState(() {
        this._isRecording = false;
      });
    } catch (err) {
      print('stopRecorder error: $err');
    }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //start();
    _noiseMeter = new NoiseMeter(onError);
  }



  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),

          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
        // player.play("2100.mp3");
        //
        // player.clearCache();
          playSound();
          start();
        },
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Any help will be much appreciated.

1

There are 1 answers

0
MαπμQμαπkγVπ.0 On

This seems to be a known error for iOS 14+ devices.

On iOS 14 and higher, enable the Dart multicast DNS service in the Debug version of your app to add debugging functionalities such as hot-reload and DevTools via flutter attach.

Check out the documentation about "Local Network Privacy Permissions". From there, I suggest to follow the instructions on enabling the Dart multicast DNS service in the Debug version of your app.