PageRenderTime 71ms CodeModel.GetById 31ms RepoModel.GetById 5ms app.codeStats 0ms

/support/phonegap-fork/android-1.5/src/com/phonegap/demo/AudioHandler.java

https://github.com/jsjohnst/moby-scheme
Java | 436 lines | 316 code | 64 blank | 56 comment | 56 complexity | e10986e991c39b10d56ad0a8b0cc0afd MD5 | raw file
  1. package com.phonegap.demo;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.BufferedInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.BufferedOutputStream;
  8. import java.net.URLConnection;
  9. import java.net.URL;
  10. import java.util.Map;
  11. import java.util.HashMap;
  12. import android.os.Handler;
  13. import android.app.Activity;
  14. import android.content.Context;
  15. import android.content.res.AssetManager;
  16. import android.content.res.AssetFileDescriptor;
  17. import android.media.AudioManager;
  18. import android.media.MediaPlayer;
  19. import android.media.MediaPlayer.OnErrorListener;
  20. import android.media.MediaRecorder;
  21. import android.media.MediaPlayer.OnBufferingUpdateListener;
  22. import android.media.MediaPlayer.OnCompletionListener;
  23. import android.media.MediaPlayer.OnPreparedListener;
  24. import android.util.Log;
  25. import android.webkit.WebView;
  26. import plt.playlist.PlaylistRecord;
  27. import plt.playlist.PlaylistPlayer;
  28. public class AudioHandler implements OnCompletionListener,
  29. OnPreparedListener,
  30. OnErrorListener {
  31. private MediaRecorder recorder;
  32. private boolean isRecording = false;
  33. // MediaPlayer mPlayer;
  34. private boolean isPlaying = false;
  35. private String recording;
  36. private String saveFile;
  37. private Activity mCtx;
  38. private Handler handler;
  39. private WebView mAppView;
  40. private ArgTable arguments;
  41. private HashMap<String, MPlayerStatus> mPlayers_file;
  42. private HashMap<MediaPlayer, MPlayerStatus> mPlayers_player;
  43. private Map<Long, PlaylistPlayer> playlistPlayers;
  44. // private boolean isPaused = false;
  45. private AssetManager assets;
  46. // private String curPlaying = null;
  47. private AudioManager volumeControl;
  48. private static final int STREAM_MUSIC = AudioManager.STREAM_MUSIC;
  49. private static final int STREAM_RING = AudioManager.STREAM_RING;
  50. private class MPlayerStatus {
  51. public String file;
  52. public MediaPlayer player;
  53. public boolean isPaused = false;
  54. public boolean isPlaying = false;
  55. public MPlayerStatus(String theFile, MediaPlayer thePlayer) {
  56. file = theFile;
  57. player = thePlayer;
  58. }
  59. }
  60. public AudioHandler(String file,
  61. Activity ctx,
  62. Handler handler,
  63. WebView appView,
  64. AssetManager assets,
  65. ArgTable args) {
  66. // this.recording = file;
  67. this.mCtx = ctx;
  68. this.handler = handler;
  69. this.mAppView = appView;
  70. this.assets = assets;
  71. this.arguments = args;
  72. volumeControl = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
  73. mPlayers_file = new HashMap<String, MPlayerStatus>();
  74. mPlayers_player = new HashMap<MediaPlayer, MPlayerStatus>();
  75. this.playlistPlayers = new HashMap<Long, PlaylistPlayer>();
  76. }
  77. /*
  78. protected void startRecording(String file){
  79. if (!isRecording){
  80. saveFile=file;
  81. recorder = new MediaRecorder();
  82. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  83. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  84. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  85. recorder.setOutputFile(this.recording);
  86. try {
  87. recorder.prepare();
  88. } catch (IllegalStateException e) {
  89. // TODO Auto-generated catch block
  90. e.printStackTrace();
  91. // } catch (IOException e) {
  92. // // TODO Auto-generated catch block
  93. // e.printStackTrace();
  94. }
  95. isRecording = true;
  96. recorder.start();
  97. }
  98. }
  99. private void moveFile(String file) {
  100. // this is a hack to save the file as the specified name
  101. File f = new File (this.recording);
  102. f.renameTo(new File("/sdcard" + file));
  103. }
  104. protected void stopRecording(){
  105. try{
  106. if((recorder != null)&&(isRecording)) {
  107. isRecording = false;
  108. recorder.stop();
  109. recorder.release();
  110. }
  111. moveFile(saveFile);
  112. }catch (Exception e){e.printStackTrace();}
  113. }
  114. */
  115. private File readStreamedUrl(String url) {
  116. try {
  117. URLConnection cn = new URL(url).openConnection();
  118. cn.connect();
  119. BufferedInputStream in = new BufferedInputStream(cn.getInputStream());
  120. // The extension actually matters to the media player.
  121. File f = File.createTempFile("play", url.substring(url.length()-4));
  122. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
  123. int ch;
  124. while ((ch = in.read()) != -1) {
  125. out.write(ch);
  126. }
  127. in.close();
  128. out.close();
  129. return f;
  130. } catch (IOException e) {
  131. throw new RuntimeException(e);
  132. }
  133. }
  134. public void playPlaylistRecord(PlaylistRecord record) {
  135. if (!playlistPlayers.containsKey(record.getId())) {
  136. PlaylistPlayer player = new PlaylistPlayer(this.mCtx,
  137. this.handler,
  138. record);
  139. playlistPlayers.put(record.getId(), player);
  140. }
  141. PlaylistPlayer player = playlistPlayers.get(record.getId());
  142. player.play();
  143. }
  144. public void pausePlaylistRecord(PlaylistRecord record) {
  145. if (playlistPlayers.containsKey(record.getId())) {
  146. PlaylistPlayer player = playlistPlayers.get(record.getId());
  147. player.pause();
  148. }
  149. }
  150. public void stopPlaylistRecord(PlaylistRecord record) {
  151. if (playlistPlayers.containsKey(record.getId())) {
  152. PlaylistPlayer player = playlistPlayers.get(record.getId());
  153. player.stop();
  154. }
  155. }
  156. protected void startPlaying(String file) {
  157. MPlayerStatus status = mPlayers_file.get(file);
  158. if ( status == null ) {
  159. try {
  160. AssetFileDescriptor fileAsset = getAssetFileDesc(file);
  161. MediaPlayer mPlayer = new MediaPlayer();
  162. mPlayer.setOnPreparedListener(this);
  163. status = new MPlayerStatus(file, mPlayer);
  164. mPlayers_file.put(file, status);
  165. mPlayers_player.put(mPlayer, status);
  166. Log.d("Audio startPlaying", "audio: " + file);
  167. if (isStreaming(file))
  168. {
  169. File f = readStreamedUrl(file);
  170. Log.d("AudioStartPlaying", "Streaming");
  171. // Streaming prepare async
  172. mPlayer.setDataSource(f.getAbsolutePath());
  173. mPlayer.setAudioStreamType(STREAM_MUSIC);
  174. mPlayer.prepare();
  175. } else {
  176. Log.d("AudioStartPlaying", "File");
  177. // Not streaming prepare synchronous, abstract base directory
  178. if (fileAsset == null) {
  179. mPlayer.setDataSource(file);
  180. }
  181. else {
  182. mPlayer.setDataSource(fileAsset.getFileDescriptor(),
  183. fileAsset.getStartOffset(),
  184. fileAsset.getLength());
  185. }
  186. mPlayer.prepare();
  187. }
  188. status.isPlaying = true;
  189. } catch (Exception e) { e.printStackTrace(); }
  190. }
  191. else if ( !status.isPlaying ) {
  192. try {
  193. status.player.prepare();
  194. status.player.start();
  195. status.isPlaying = true;
  196. status.isPaused = false;
  197. } catch (Exception e) { e.printStackTrace(); }
  198. }
  199. // Otherwise check to see if it's paused, if it is, resume
  200. else if ( status.isPaused ) {
  201. status.player.start();
  202. status.isPaused = false;
  203. }
  204. }
  205. private AssetFileDescriptor getAssetFileDesc(String file) {
  206. if ( !file.startsWith("file:///android_asset/") ) {
  207. return null;
  208. }
  209. try {
  210. String filePath = file.substring(22);
  211. return assets.openFd(filePath);
  212. } catch (IOException e) {
  213. e.printStackTrace();
  214. return null;
  215. }
  216. }
  217. protected void pausePlaying(String file) {
  218. MPlayerStatus status = mPlayers_file.get(file);
  219. if ( status != null && status.isPlaying && !status.isPaused ) {
  220. status.player.pause();
  221. status.isPaused = true;
  222. }
  223. }
  224. protected void resumePlaying(String file) {
  225. MPlayerStatus status = mPlayers_file.get(file);
  226. if ( status != null && status.isPaused ) {
  227. status.player.start();
  228. status.isPaused = false;
  229. }
  230. }
  231. protected void stopPlaying(String file) {
  232. // System.out.println("stopPlaying called");
  233. MPlayerStatus status = mPlayers_file.get(file);
  234. if ( status != null ) {
  235. status.player.stop();
  236. status.isPlaying = false;
  237. status.isPaused = false;
  238. }
  239. }
  240. public void onCompletion(MediaPlayer mPlayer) {
  241. // System.out.println("onCompletion called");
  242. MPlayerStatus status = mPlayers_player.get(mPlayer);
  243. mPlayer.stop();
  244. status.isPlaying = false;
  245. status.isPaused = false;
  246. arguments.put("finishedMusicFile", status.file);
  247. // String escapedFile = status.file.replaceAll("'", "\\\\'");
  248. mAppView.loadUrl("javascript:navigator.audio.musicFinished()");
  249. // System.out.println("Called musicFinished on " + escapedFile);
  250. }
  251. public void stopAllPlaying() {
  252. // System.out.println("stopAllPlaying called");
  253. for ( MPlayerStatus status : mPlayers_file.values() ) {
  254. status.player.stop();
  255. status.isPlaying = false;
  256. status.isPaused = false;
  257. }
  258. for (Long id : playlistPlayers.keySet()) {
  259. playlistPlayers.get(id).stop();
  260. }
  261. }
  262. public void clearCache() {
  263. // System.out.println("clearCache called");
  264. for (MediaPlayer player : mPlayers_player.keySet()) {
  265. player.stop();
  266. player.release();
  267. }
  268. mPlayers_file.clear();
  269. mPlayers_player.clear();
  270. }
  271. public void increaseVolume(int flags) {
  272. volumeControl.adjustStreamVolume(STREAM_MUSIC,
  273. AudioManager.ADJUST_RAISE,
  274. flags);
  275. }
  276. public void decreaseVolume(int flags) {
  277. volumeControl.adjustStreamVolume(STREAM_MUSIC,
  278. AudioManager.ADJUST_LOWER,
  279. flags);
  280. }
  281. public boolean setVolume(int percent, int flags) {
  282. if (percent < 0 || percent > 100)
  283. return false;
  284. int volIndex = percent * volumeControl.getStreamMaxVolume(STREAM_MUSIC) / 100;
  285. volumeControl.setStreamVolume(STREAM_MUSIC, volIndex, flags);
  286. return true;
  287. }
  288. public boolean setRingerVolume(int percent, int flags) {
  289. if (percent < 0 || percent > 100)
  290. return false;
  291. int volIndex = percent * volumeControl.getStreamMaxVolume(STREAM_MUSIC) / 100;
  292. volumeControl.setStreamVolume(STREAM_RING, volIndex, flags);
  293. return true;
  294. }
  295. protected long getCurrentPosition(String file) {
  296. MediaPlayer mPlayer = mPlayers_file.get(file).player;
  297. if (mPlayer != null)
  298. {
  299. return(mPlayer.getCurrentPosition());
  300. } else { return(-1); }
  301. }
  302. private boolean isStreaming(String file)
  303. {
  304. if (file.contains("http://")) {
  305. return true;
  306. } else {
  307. return false;
  308. }
  309. }
  310. protected long getDuration(String file) {
  311. long duration = -2;
  312. if (!mPlayers_file.containsKey(file) & !isStreaming(file)) {
  313. try {
  314. AssetFileDescriptor fileAsset = getAssetFileDesc(file);
  315. MediaPlayer mPlayer = new MediaPlayer();
  316. if (fileAsset == null) {
  317. mPlayer.setDataSource(file);
  318. }
  319. else {
  320. mPlayer.setDataSource(fileAsset.getFileDescriptor());
  321. }
  322. mPlayer.prepare();
  323. duration = mPlayer.getDuration();
  324. mPlayer.release();
  325. } catch (Exception e) { e.printStackTrace(); return(-3); }
  326. } else if (mPlayers_file.containsKey(file)) {
  327. try {
  328. duration = mPlayers_file.get(file).player.getDuration();
  329. } catch (Exception e) { e.printStackTrace(); return(-4); }
  330. } else { return -1; }
  331. return duration;
  332. }
  333. public void onPrepared(MediaPlayer mPlayer) {
  334. if ( mPlayers_player.containsKey(mPlayer) ) {
  335. mPlayer.setOnCompletionListener(this);
  336. mPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener()
  337. {
  338. public void onBufferingUpdate(MediaPlayer mPlayer, int percent)
  339. {
  340. /* TODO: call back, e.g. update outer progress bar */
  341. Log.d("AudioOnBufferingUpdate", "percent: " + percent);
  342. }
  343. });
  344. mPlayer.start();
  345. }
  346. }
  347. public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
  348. Log.e("AUDIO onError", "error " + arg1 + " " + arg2);
  349. return false;
  350. }
  351. protected void setAudioOutputDevice(int output){
  352. // Changes the default audio output device to speaker or earpiece
  353. AudioManager audiMgr = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
  354. if (output == (2))
  355. audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);
  356. else if (output == (1)){
  357. audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
  358. }else
  359. Log.e("AudioHandler setAudioOutputDevice", " unknown output device");
  360. }
  361. protected int getAudioOutputDevice(){
  362. AudioManager audiMgr = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
  363. if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE)
  364. return 1;
  365. else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER)
  366. return 2;
  367. else
  368. return -1;
  369. }
  370. }