首页 文章

Phonegap Media API - 录制和播放音频 - Android

提问于
浏览
7

我希望录制一些音频,然后才能播放它 . 能够customize the record interface对我来说很重要 .

在录制后的下面示例中,我得到-1的持续时间并且没有播放音频 .

Step 1. 已添加Media Plugin

cordova plugin add org.apache.cordova.media

Step 2. 我的代码

注意src是文档中请求的“amr” .

Android设备以自适应多速率格式录制音频 . 指定的文件应以.amr扩展名结尾 .

但是,我的文件结构中不存在“myrecording.amr”,因为我希望它会被创建 .

Javascript

var data = {
  rec: ""
};
$scope.record = function(){
    console.log('record');
    var src = "myrecording.amr";
    data.rec = new Media(src,
    function() {
      console.log("recordAudio():Audio Success");
    },

    function(err) {
      console.log("recordAudio():Audio Error: "+ err.code);
    });

    data.rec.startRecord();
}

$scope.stopRecording = function(){
    console.log('stop');
    data.rec.stopRecord();
}

$scope.playRecording = function(){
    console.log('play');
    data.rec.play();
}

$scope.logDuration = function(){
    console.log(data.rec.getDuration());
}

HTML

<button ng-click="record()">Record</button>
<button ng-click="stopRecording()">Stop Record</button>
<button ng-click="playRecording()">Play Record</button>
<button ng-click="logDuration()">Log Duration</button>

Output From Above

点击播放时没有播放音频 .

0     999846   log      record
1     001845   log      stop
2     002000   log      recordAudio():Audio Success
3     004657   log      play
4     008989   log      -1

任何帮助将不胜感激 . 如果我能回答任何问题,请告诉我 .

2 回答

  • 7

    以下是我的工作步骤 .

    1.运行这些命令

    ionic start RecordTest blank
    ionic platform add ios
    cordova plugin add org.apache.cordova.media
    

    2.创建RecordTest / www / myrecording.wav

    3.将以下代码粘贴到RecordTest / www / index.html中

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
    
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
    
        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
        <link href="css/ionic.app.css" rel="stylesheet">
        -->
    
        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.js"></script>
    
        <!-- cordova script (this will be a 404 during development) -->
        <script src="cordova.js"></script>
    
        <!-- your app's js -->
        <!-- <script src="js/app.js"></script> -->
        <script type="text/javascript" charset="utf-8">
    
        // Wait for PhoneGap to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);
    
        // Record audio
        // 
        function recordAudio() {
            var src = "myrecording.wav";
            var mediaRec = new Media(src, onSuccess, onError);
    
            // Record audio
            mediaRec.startRecord();
    
            // Stop recording after 10 sec
            var recTime = 0;
            var recInterval = setInterval(function() {
                recTime = recTime + 1;
                setAudioPosition(recTime + " sec");
                if (recTime >= 3) {
                    clearInterval(recInterval);
                    mediaRec.stopRecord();
                    mediaRec.play();
                }
            }, 1000);
        }
    
        // PhoneGap is ready
        //
        function onDeviceReady() {
            recordAudio();
        }
    
        // onSuccess Callback
        //
        function onSuccess() {
            console.log("recordAudio():Audio Success");
        }
    
        // onError Callback 
        //
        function onError(error) {
            alert('code: '    + error.code    + '\n' + 
                  'message: ' + error.message + '\n');
        }
    
        // Set audio position
        // 
        function setAudioPosition(position) {
            document.getElementById('audio_position').innerHTML = position;
        }
        </script>
      </head>
      <body ng-app="starter">
        <ion-pane>
          <ion-header-bar class="bar-stable">
            <h1 class="title">Ionic Blank Starter</h1>
          </ion-header-bar>
          <ion-content>
              <title>Device Properties Example</title>
              <!-- <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script> -->
              <p id="media">Recording audio...</p>
              <p id="audio_position"></p>
          </ion-content>
        </ion-pane>
      </body>
    </html>
    

    4.运行离子模拟ios

    以上应该有效 .

    Note: the extension changes depending on the platform you're developing for

  • 2

    我正在使用与ionicframworkf和phonegap插件类似的东西..我 Build 了一个记录工厂:

    startRecord,stopRecord,playRecord和Save记录到服务器......这是我的工厂文件:

    /**
     * Record service
     * @module record
     * @author Claudio A. Marrero
     * @class famvoice
     */
     services.factory('$record', [
    
      '$rootScope',
      '$socket',
      '$account',
    
      function($rootScope, $socket, $account) {
    
        var enumerator = 0;
        var recordName = 'record-'+enumerator+'.mp3';
        var mediaRec = null;
        var OnCallback = null;
        var OnAppendData = {};
    
        /**
        * Start a record
        *
        * @method startRecord
        */
        function startRecord(){
          enumerator++;
          recordName = 'record-'+enumerator+'.mp3';
          mediaRec = new Media(recordName,
              function() {
              },
              function(err) {
              });
          mediaRec.startRecord();
        }
    
        /**
        * Stop record
        *
        * @method stopRecord
        */
        function stopRecord(){
          mediaRec.stopRecord();
        }
    
        /**
        * Stop record
        *
        * @method stopRecord
        */
        function playRecord(){
          mediaRec.play();
        }
    
        /**
        * Get the name of the record
        *
        * @method getRecord
        */
        function getRecord(){
          return recordName;
        }
    
        /**
        * Save the recorded file to the server
        *
        * @method save
        */
        function save(callback,appendData){
          OnCallback = callback;
          OnAppendData = appendData;
          window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, OnFileSystem, fail);
        }
    
        /**
        * Callback for setting the file system to persistent.
        *
        * @method OnFileSystem
        */
        function OnFileSystem(fileSystem){
          fileSystem.root.getFile(recordName, null, OnGetFile, fail);
        }
    
        /**
        * Callback for geting the file for disk
        *
        * @method OnGetFile
        */
        function OnGetFile(fileEntry){
          fileEntry.file(OnFileEntry, fail);
        }
    
        /**
        * Callback for file entry, this get the file.
        *
        * @method OnFileEntry
        */
        function OnFileEntry(file){
          var reader = new FileReader();
          reader.onloadend = function(evt) {
    
              var image = evt.target.result;
              var base64Data  =   image.replace(/^data:audio\/mpeg;base64,/, "");
              base64Data  +=  base64Data.replace('+', ' ');
    
              $socket.emit('playlists:file',{file:base64Data,name:recordName, token: $account.token(), info:OnAppendData},OnCallback);
          };
          reader.readAsDataURL(file);
        }
    
        /**
        * When any process of saving file fail, this console the error.
        *
        * @method OnFileEntry
        */
        function fail(err){
          console.log('Error');
          console.log(err);
        }
    
        /**
        * Play record
        *
        * @method playRecord
        */
        function playRecord(){
          var mediaFile = new Media(recordName,
              function() {
                console.log("playAudio():Audio Success");
              },
              function(err) {
                console.log("playAudio():Audio Error: "+err);
              }
          );
          // Play audio
          mediaFile.play();
        }
    
      return {
        start: startRecord,
        stop: stopRecord,
        play:playRecord,
        name:getRecord,
        save:save
      };
    }]);
    

    如果你想检查我如何实现这个工厂,我的项目在GitHub上:

    https://github.com/cmarrero01/famvoice

    您需要签出开发分支 .

    我希望这对你来说很有用 . :)

    PH:关于代码请求,我注意到这个问题,但我不是一个好的英语演讲者 . :)

相关问题