0

我正在尝试使用 phonegap 中的 Media 对象录制音频文件,然后播放它。我录制没有问题,但是当我尝试播放它时,我的应用程序在我的模拟器和设备上都关闭了。在 logcat 上它说:“org.apache.cordova.readyPlayer (AudioPlayer.java) 处的空指针异常”。非常感谢任何愿意帮助我的人,我花了一段时间才意识到我在这里完全迷失了。这是我从http://docs.phonegap.com/en/2.4.0/cordova_media_media.md.html#media.stopRecord复制并在 .stopRecord() 之后添加的代码。如果需要,我可以添加清单和活动,我怀疑问题是否存在,但我可能是错的。 索引.html:

<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" charset="utf-8">

// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// Record audio
// 
function recordAudio() {
    var src = "myrecording.amr";
    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 >= 10) {
            clearInterval(recInterval);
            mediaRec.stopRecord();
            document.getElementById('audio_position').innerHTML = "finished";
            **mediaRec.play();**
        }
    }, 1000);
}

// Cordova 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>

<p id="media">Recording audio...</p>
<p id="audio_position"></p>

尤瓦尔

4

2 回答 2

3

我在 Cordova 3.5(使用媒体插件 0.2.11)和 Android 4.4 中发现了同样的问题。解决方法如上所述。基本上这样的事情应该可以解决问题:

mediaRec.stopRecord();
src = mediaRec.src;  // if you don't have src defined anymore
mediaRec.release();

mediaPlay = new Media(src, onSuccess, onError);
mediaPlay.play();
于 2014-07-17T18:35:55.203 回答
1

无需创建其他媒体对象来播放之前录制的文件。只需执行以下操作 - 您必须在录制停止后释放媒体对象:

// variable in global scope
var mediaRec = 0;

// function to record an audio
function recordAudio() {
  // create media object for your recording
  mediaRec = new Media("phonegap_rec.amr", onMediaRecordSuccess, onMediaRecordError);
  // start recording
  mediaRec.startRecord();
  // recording for 5 seconds
  var recTime = 0;
    var recInterval = setInterval(function() {
        recTime = recTime + 1;
        if (recTime >= 5) {
            clearInterval(recInterval);
            // stop recording after 5 seconds
            mediaRec.stopRecord();
            // release the media object (THIS IS THE KEY SOLUTION HERE)
            mediaRec.release();
        }
    }, 1000);
}

// function to playback recorded audio
function playRecord() {
  // check if the object exists
  if (mediaRec) {
    // now you can playback the recording
    mediaRec.play();
  }
}

于 2015-02-19T17:37:30.050 回答