A6plus-Global
@ 32
A6plus-Global / trunk / Mobile / phonegap-2.5.0 / lib / blackberry / framework / ext / src / org / apache / cordova / media / AudioPlayer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 |
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cordova.media; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; import javax.microedition.media.Manager; import javax.microedition.media.MediaException; import javax.microedition.media.Player; import javax.microedition.media.PlayerListener; import javax.microedition.media.control.RecordControl; import javax.microedition.media.control.VolumeControl; import javax.microedition.media.protocol.DataSource; import net.rim.device.api.media.protocol.ByteArrayInputStreamDataSource; import org.apache.cordova.util.FileUtils; import org.apache.cordova.util.Logger; /** * This class implements the audio playback and recording capabilities used by * Cordova. It is called by the Media Cordova class. Only one file can be played * or recorded per class instance. * * Supports playing audio locally and remotely. Files located within the * application package must be prefixed with "local:///". If no URI prefix * (file, http, local) is found, file is assumed to be on device and "file:///" * prefix added. */ public class AudioPlayer implements PlayerListener { private static final String LOG_TAG = "AudioPlayer: "; // Media states public static final int MEDIA_NONE = 0; public static final int MEDIA_STARTING = 1; public static final int MEDIA_RUNNING = 2; public static final int MEDIA_PAUSED = 3; public static final int MEDIA_STOPPED = 4; // Media message ids private static final int MEDIA_STATE = 1; private static final int MEDIA_DURATION = 2; private static final int MEDIA_POSITION = 3; private static final int MEDIA_ERROR = 9; // Media error codes private static final int MEDIA_ERR_NONE_ACTIVE = 0; private static final int MEDIA_ERR_ABORTED = 1; private static final int MEDIA_ERR_NETWORK = 2; private static final int MEDIA_ERR_DECODE = 3; private static final int MEDIA_ERR_NONE_SUPPORTED = 4; private final Media handler; private final String id; private int state = MEDIA_NONE; // State of recording or playback private String audioFile = null; // File name to play or record to private float duration = -1; // Duration of audio private Player recorder = null; // Audio recording object private RecordControl recorderControl = null; private ByteArrayOutputStream recorderOutput = null; private Player player = null; // Audio player object private boolean prepareOnly = false; private long prevPos = 0; private long adjustTime = 0; private long previousTime = 0; private long lastPlay = System.currentTimeMillis(); private boolean buffering = false; /** * Constructor. * * @param handler * The audio handler object * @param id * The id of this audio player */ public AudioPlayer(Media handler, String id) { this.handler = handler; this.id = id; } /** * Destroy stop audio playing or recording and free resources. */ public synchronized void destroy() { // Stop any play or record destroyPlayer(); if (recorder != null) { stopRecording(); } } /** * Stop and free the player. */ private void destroyPlayer() { if (player != null) { if (state == MEDIA_RUNNING || state == MEDIA_PAUSED) { stopPlaying(); } player.removePlayerListener(this); player.close(); player = null; } } /** * Get current position of playback. * * @return position as a floating point number indicating number of seconds * or -1 if not playing */ public synchronized float getCurrentPosition() { // Current position is only valid when running, paused or buffering. if (state == MEDIA_RUNNING || state == MEDIA_PAUSED || buffering) { // The time returned by getMediaTime() is only updated every second. // Keep track of time between updates in order to provide // millisecond granularity. long curPos = player.getMediaTime(); // Media time is within the 1 second granularity window so add time // since last update. if (curPos == prevPos && state == MEDIA_RUNNING) { if (previousTime == 0) { previousTime = System.currentTimeMillis(); } else { long newTime = System.currentTimeMillis(); // Convert from milliseconds to microseconds. adjustTime += ((newTime - previousTime) * 1000); previousTime = newTime; curPos += adjustTime; } } else { prevPos = curPos; previousTime = System.currentTimeMillis(); adjustTime = 0; } // Convert from microseconds to floating point seconds. float time = curPos / 1000000.0f; sendStatus(MEDIA_POSITION, time); return time; } else { return -1; } } /** * Get the duration of the audio file. * * @param file * The name of the audio file. * @return duration as a floating point number indicating number of seconds * or -1 = can't be determined or -2 = not allowed */ public synchronized float getDuration(String file) { // Can't get duration of recording if (recorder != null) { return (-2); // not allowed } // If audio file already loaded and started, then return duration if (player != null) { return duration; } // If no player yet, then create one else { prepareOnly = true; startPlaying(file); // This will only return value for local, since streaming // file hasn't been read yet. return duration; } } /** * Get the audio state. * * @return int */ public synchronized int getState() { return state; } /** * Pause playing. */ public synchronized void pausePlaying() { // If playing, then pause if (state == MEDIA_RUNNING) { try { player.stop(); setState(MEDIA_PAUSED); } catch (MediaException e) { Logger.log(LOG_TAG + "pausePlaying() Error: " + e.getMessage()); sendError(MEDIA_ERR_ABORTED); } } else { Logger.log(LOG_TAG + "pausePlaying() Error: called during invalid state: " + state); sendError(MEDIA_ERR_NONE_ACTIVE); } } /** * PlayerListener interface callback when an event occurs in the player. * * @see javax.microedition.media.PlayerListener#playerUpdate(javax.microedition.media.Player, * java.lang.String, java.lang.Object) */ public void playerUpdate(Player player, String event, Object eventData) { if (BUFFERING_STARTED.equals(event)) { buffering = true; } else if (BUFFERING_STOPPED.equals(event)) { buffering = false; setState(MEDIA_RUNNING); } else if (DURATION_UPDATED.equals(event)) { if (eventData != null && eventData instanceof Long) { // Convert duration from microseconds to seconds. duration = ((Long) eventData).longValue() / 1000000.0f; sendStatus(MEDIA_DURATION, duration); } } else if (END_OF_MEDIA.equals(event)) { // Update the final position before stopping the player. if (eventData != null && eventData instanceof Long) { sendStatus(MEDIA_POSITION, ((Long) eventData).longValue() / 1000000.0f); } stopPlaying(); } else if (ERROR.equals(event)) { // Send error notification to JavaScript if (eventData != null && eventData instanceof String) { try { int code = Integer.parseInt((String) eventData); sendError(code); } catch (NumberFormatException ne) { Logger.log(LOG_TAG + "playerUpdate(): Player id(" + id + ") received error: " + eventData); } } else { Logger.log(LOG_TAG + "playerUpdate(): Player id(" + id + ") received error: " + eventData); } destroy(); } } /** * Seek or jump to a new time in the track. * * @throws MediaException */ public synchronized void seekToPlaying(int milliseconds) { if (player != null) { try { // Convert milliseconds to microseconds. player.setMediaTime(milliseconds > 0 ? milliseconds * 1000 : milliseconds); sendStatus(MEDIA_POSITION, milliseconds / 1000.0f); } catch (MediaException e) { Logger.log(LOG_TAG + "seekToPlaying() Error: " + e.getMessage()); sendError(MEDIA_ERR_ABORTED); } } } /** * Set the volume for audio player * * @param volume * volume level 0.0-1.0 */ public synchronized void setVolume(float volume) { if (player != null) { if (player.getState() >= Player.REALIZED) { VolumeControl vc = (VolumeControl) player .getControl("VolumeControl"); // Native volume level range is 0-100 vc.setLevel((int) (volume * 100)); } } } /** * Start or resume playing audio file. * * @param file * The name of the audio file. */ public synchronized void startPlaying(String file) { try { if (recorder != null) { Logger.log(LOG_TAG + "startPlaying() Error: Can't play in record mode."); sendError(MEDIA_ERR_ABORTED); } // If this is a new request to play audio, or stopped else if (player == null || state == MEDIA_STOPPED) { setState(MEDIA_STARTING); if (file == null || file.length() == 0) { Logger.log(LOG_TAG + "startPlaying(): Input file not specified."); sendError(MEDIA_ERR_ABORTED); setState(MEDIA_NONE); destroy(); return; } // If the player was previously used, need to check if it needs // recreated to pick up file changes. Cases when the player // needs recreated: // 1. New source file was specified. // 2. File is local and has been modified since last play. if (player != null) { if (!file.equals(audioFile)) { destroyPlayer(); } else if (!isStreaming(file)) { // File needs to follow the local or file URI protocol // so if neither prefix exists assume a file URI and add // the "file:///" prefix. file = FileUtils.prefixFileURI(file); FileConnection fconn = null; try { fconn = (FileConnection) Connector.open(file, Connector.READ); if (fconn.exists()) { if (fconn.lastModified() > lastPlay) { destroyPlayer(); } } } catch (Exception e) { // Ignore } finally { try { if (fconn != null) { fconn.close(); } } catch (IOException ignored) { } } } } // At this point if player is not null then the file previously // played is still valid so just reset the current position. if (player != null) { player.setMediaTime(0); } // Otherwise, create a new one else { // If streaming file if (isStreaming(file)) { player = Manager.createPlayer(file); } else { // File needs to follow the local or file URI protocol // so if neither prefix exists assume a file URI and add // the "file:///" prefix. file = FileUtils.prefixFileURI(file); String contentType = "audio/mp3"; if (file.endsWith(".amr")) { contentType = "audio/amr"; } else if (file.endsWith(".wav")) { contentType = "audio/wav"; } DataSource dataSource = new ByteArrayInputStreamDataSource( new ByteArrayInputStream(FileUtils.readFile( file, Connector.READ)), contentType); player = Manager.createPlayer(dataSource); } audioFile = file; player.addPlayerListener(this); } lastPlay = System.currentTimeMillis(); player.realize(); player.prefetch(); // Get duration as floating point seconds. duration = player.getDuration() == Player.TIME_UNKNOWN ? Player.TIME_UNKNOWN : player.getDuration() / 1000000.0f; sendStatus(MEDIA_DURATION, duration); if (!prepareOnly) { player.start(); } prepareOnly = false; } // If previously existing player is still valid. else { // If player has been paused, then resume playback if (state == MEDIA_PAUSED || state == MEDIA_STARTING) { player.start(); setState(MEDIA_RUNNING); } else { Logger.log(LOG_TAG + "Error: startPlaying() called during invalid state: " + state); sendError(MEDIA_ERR_ABORTED); } } } catch (Exception e) { e.printStackTrace(); Logger.log(LOG_TAG + "startPlaying() Error: " + e.getMessage()); sendError(MEDIA_ERR_ABORTED); } } /** * Start recording the specified file. * * @param file * The name of the file */ public synchronized void startRecording(String file) { try { if (player != null) { Logger.log(LOG_TAG + "startRecording() Error: Can't record in play mode."); sendError(MEDIA_ERR_ABORTED); } else if (recorder == null) { if (file == null || file.length() == 0) { Logger.log(LOG_TAG + "startRecording() Error: Output file not specified."); sendError(MEDIA_ERR_ABORTED); return; } setState(MEDIA_STARTING); file = FileUtils.prefixFileURI(file); recorder = Manager.createPlayer("capture://audio"); recorder.addPlayerListener(this); recorder.realize(); recorderControl = (RecordControl) recorder .getControl("RecordControl"); recorderOutput = new ByteArrayOutputStream(); recorderControl.setRecordStream(recorderOutput); recorderControl.startRecord(); recorder.start(); audioFile = file; setState(MEDIA_RUNNING); } else { Logger.log(LOG_TAG + "startRecording() Error: Already recording."); sendError(MEDIA_ERR_ABORTED); } } catch (Exception e) { Logger.log(LOG_TAG + "startRecording() Error: Failed to start recording. " + e.getMessage()); if (recorder != null) { recorder.removePlayerListener(this); recorder.close(); recorder = null; } if (recorderControl != null) { try { recorderControl.reset(); } catch (IOException e1) { // Ignore } recorderControl = null; } if (recorderOutput != null) { try { recorderOutput.close(); } catch (IOException e1) { // Ignore } recorderOutput = null; } setState(MEDIA_NONE); } } /** * Stop playing the audio file. */ public synchronized void stopPlaying() { if (state == MEDIA_RUNNING || state == MEDIA_PAUSED) { try { player.stop(); player.setMediaTime(0); } catch (MediaException e) { Logger.log(LOG_TAG + "stopPlaying() Error: " + e.getMessage()); sendError(MEDIA_ERR_ABORTED); } setState(MEDIA_STOPPED); } else { Logger.log(LOG_TAG + "stopPlaying() called during invalid state: " + state); sendError(MEDIA_ERR_NONE_ACTIVE); } } /** * Stop recording and save to the file specified when recording started. */ public synchronized void stopRecording() { DataOutputStream output = null; FileConnection conn = null; try { if (recorder != null) { if (state == MEDIA_RUNNING) { recorderControl.commit(); byte data[] = recorderOutput.toByteArray(); conn = (FileConnection) Connector.open(audioFile, Connector.READ_WRITE); if (conn.exists()) { conn.delete(); conn.close(); conn = (FileConnection) Connector.open(audioFile, Connector.READ_WRITE); } conn.create(); output = conn.openDataOutputStream(); output.write(data); output.flush(); } } } catch (IOException e) { // Ignore Logger.log(LOG_TAG + "stopRecording() Error: " + e.getMessage()); } finally { if (recorderOutput != null) { try { recorderOutput.close(); } catch (IOException e) { // Ignore Logger.log(LOG_TAG + "stopRecording() Failed to close recorder output. " + e.getMessage()); } recorderOutput = null; } if (recorder != null) { recorder.removePlayerListener(this); recorder.close(); recorder = null; } if (recorderControl != null) { recorderControl.stopRecord(); recorderControl = null; } if (output != null) { try { output.close(); } catch (IOException e) { // Ignore Logger.log(LOG_TAG + "stopRecording() Failed to close output file. " + e.getMessage()); } output = null; } if (conn != null) { try { conn.close(); } catch (IOException e) { // Ignore Logger.log(LOG_TAG + "stopRecording() Failed to close connection. " + e.getMessage()); } } setState(MEDIA_STOPPED); } } /** * Determine if playback file is streaming or local. It is streaming if file * name starts with "http://" * * @param file * The file name * @return T=streaming, F=local */ private boolean isStreaming(String file) { if (file.startsWith("http://") || file.startsWith("https://")) { return true; } return false; } private void sendError(int code) { handler.invokeScript("cordova.require('cordova/plugin/Media').onStatus('" + id + "', " + MEDIA_ERROR + ", { \"code\":" + code + "});"); } private void sendStatus(int msg, float value) { handler.invokeScript("cordova.require('cordova/plugin/Media').onStatus('" + id + "', " + msg + ", " + value + ");"); } private void sendStatus(int msg, int value) { handler.invokeScript("cordova.require('cordova/plugin/Media').onStatus('" + id + "', " + msg + ", " + value + ");"); } /** * Set the state and send it to JavaScript. * * @param state */ private synchronized void setState(int state) { // Only send state back to JavaScript if it has changed. if (this.state != state) { sendStatus(MEDIA_STATE, state); } this.state = state; } } |