hokshmax / pcmtowav

realtime pcm to wav convreter with dart
Apache License 2.0
2 stars 1 forks source link

bump the example #1

Open lantos1618 opened 6 months ago

lantos1618 commented 6 months ago
import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:record/record.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:pcmtowave/convertToWav.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Hello ${_user?.displayName ?? "Guest"}",
            ),
            AudioPlayerWidget(),
          ],
        ),
      ),
    );
  }
}

class AudioPlayerWidget extends StatefulWidget {
  const AudioPlayerWidget({super.key});

  @override
  State<AudioPlayerWidget> createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
  final _pcmtowave =
      convertToWav(sampleRate: 44100, converMiliSeconds: 1000, numChannels: 2);
  final record = AudioRecorder();
  final player = AudioPlayer();

  bool isRecording = false;
  bool isPlaying = false;

  Uint8List? data = null;

  @override
  void initState() {
    super.initState();

    _pcmtowave.convert.listen((event) async {
      if (data == null) {
        data = event;
      } else {
        data = Uint8List.fromList(data! + event);
      }

      setState(() {});
    });
  }

  startRecording() async {
    if (await record.hasPermission()) {
      if (!isRecording) {
        print("recording");
        data = Uint8List(0);
        final stream = await record
            .startStream(const RecordConfig(encoder: AudioEncoder.pcm16bits));
        isRecording = true;

        stream.listen((event) {
          _pcmtowave.run(event);
        });
      }
    }
    setState(() {});
  }

  stopRecording() async {
    if (isRecording) {
      record.stop();
      isRecording = false;
    }
    setState(() {});
  }

  startPlaying() async {
    if (data != null) {
      print("playing");
      var source = BytesSource(data!, mimeType: "audio/wav");
      await player.play(source);
    }
    setState(() {});
  }

  stopPlaying() async {
    if (isPlaying) {
      player.stop();
      isPlaying = false;
    }
    setState(() {});
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          margin: const EdgeInsets.all(3),
          padding: const EdgeInsets.all(3),
          height: 80,
          width: double.infinity,
          alignment: Alignment.center,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
            ElevatedButton(
              onPressed: () {
                if (!isRecording) {
                  startRecording();
                } else {
                  stopRecording();
                }
              },
              //color: Colors.white,
              //disabledColor: Colors.grey,
              child: Text(isRecording ? 'Stop' : 'Record'),
            ),
            ElevatedButton(
                onPressed: () {
                  if (!isPlaying) {
                    startPlaying();
                  } else {
                    stopPlaying();
                  }
                },
                child: Text(isPlaying ? "Stop" : "Play")),
          ]),
        ),
      ],
    );
  }
}
zamirszn commented 4 months ago
import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:record/record.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:pcmtowave/convertToWav.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Hello ${_user?.displayName ?? "Guest"}",
            ),
            AudioPlayerWidget(),
          ],
        ),
      ),
    );
  }
}

class AudioPlayerWidget extends StatefulWidget {
  const AudioPlayerWidget({super.key});

  @override
  State<AudioPlayerWidget> createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
  final _pcmtowave =
      convertToWav(sampleRate: 44100, converMiliSeconds: 1000, numChannels: 2);
  final record = AudioRecorder();
  final player = AudioPlayer();

  bool isRecording = false;
  bool isPlaying = false;

  Uint8List? data = null;

  @override
  void initState() {
    super.initState();

    _pcmtowave.convert.listen((event) async {
      if (data == null) {
        data = event;
      } else {
        data = Uint8List.fromList(data! + event);
      }

      setState(() {});
    });
  }

  startRecording() async {
    if (await record.hasPermission()) {
      if (!isRecording) {
        print("recording");
        data = Uint8List(0);
        final stream = await record
            .startStream(const RecordConfig(encoder: AudioEncoder.pcm16bits));
        isRecording = true;

        stream.listen((event) {
          _pcmtowave.run(event);
        });
      }
    }
    setState(() {});
  }

  stopRecording() async {
    if (isRecording) {
      record.stop();
      isRecording = false;
    }
    setState(() {});
  }

  startPlaying() async {
    if (data != null) {
      print("playing");
      var source = BytesSource(data!, mimeType: "audio/wav");
      await player.play(source);
    }
    setState(() {});
  }

  stopPlaying() async {
    if (isPlaying) {
      player.stop();
      isPlaying = false;
    }
    setState(() {});
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          margin: const EdgeInsets.all(3),
          padding: const EdgeInsets.all(3),
          height: 80,
          width: double.infinity,
          alignment: Alignment.center,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
            ElevatedButton(
              onPressed: () {
                if (!isRecording) {
                  startRecording();
                } else {
                  stopRecording();
                }
              },
              //color: Colors.white,
              //disabledColor: Colors.grey,
              child: Text(isRecording ? 'Stop' : 'Record'),
            ),
            ElevatedButton(
                onPressed: () {
                  if (!isPlaying) {
                    startPlaying();
                  } else {
                    stopPlaying();
                  }
                },
                child: Text(isPlaying ? "Stop" : "Play")),
          ]),
        ),
      ],
    );
  }
}

hello , can i use this sample for a production app im trying to convert pcm to wav for my audio stream ?

hokshmax commented 4 months ago

Yes you can