Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.96 KB | None | 0 0
  1. //MainAvtivity
  2. package com.example.media;
  3.  
  4. import android.Manifest;
  5. import android.content.pm.PackageManager;
  6. import android.media.AudioManager;
  7. import android.media.MediaPlayer;
  8. import android.media.MediaRecorder;
  9. import android.media.audiofx.Visualizer;
  10. import android.net.Uri;
  11. import android.os.Handler;
  12. import android.os.Message;
  13. import android.os.Bundle;
  14. import android.util.Log;
  15. import android.view.View;
  16. import android.widget.AdapterView;
  17. import android.widget.ArrayAdapter;
  18. import android.widget.Button;
  19. import android.widget.SeekBar;
  20. import android.widget.Spinner;
  21. import android.widget.TextView;
  22. import android.widget.Toast;
  23. import androidx.appcompat.app.AppCompatActivity;
  24. import androidx.core.app.ActivityCompat;
  25.  
  26. import com.example.media.R;
  27. import com.example.media.VisualizerView;
  28.  
  29. import java.io.IOException;
  30.  
  31. public class MainActivity extends AppCompatActivity {
  32.  
  33. Button playBtn;
  34. SeekBar positionBar;
  35. SeekBar volumeBar;
  36. TextView elapsedTimeLabel;
  37. TextView remainingTimeLabel;
  38. MediaPlayer mp;
  39. int totalTime;
  40. Spinner dropdown;
  41. final String[] items = {"music_mp3", "music_amr", "music_flac", "music_m4a", "music_m4r", "music_mp2", "music_ogg", "music_wav"};
  42. private Button play, stop, record;
  43. private MediaRecorder myAudioRecorder;
  44. private String outputFile;
  45. VisualizerView mVisualizerView;
  46. private Visualizer mVisualizer;
  47.  
  48. @Override
  49. protected void onCreate(Bundle savedInstanceState) {
  50.  
  51. super.onCreate(savedInstanceState);
  52. setContentView(R.layout.activity_main);
  53.  
  54. playBtn = (Button) findViewById(R.id.playBtn);
  55. elapsedTimeLabel = (TextView) findViewById(R.id.elapsedTimeLabel);
  56. remainingTimeLabel = (TextView) findViewById(R.id.remainingTimeLabel);
  57. positionBar = (SeekBar) findViewById(R.id.positionBar);
  58. volumeBar = (SeekBar) findViewById(R.id.volumeBar);
  59.  
  60. // Media Player
  61. mp = MediaPlayer.create(this, Uri.parse("android.resource://com.example.media/raw/" + items[0]));
  62. mp.setLooping(true);
  63. mp.seekTo(0);
  64. mp.setVolume(0.5f, 0.5f);
  65. totalTime = mp.getDuration();
  66.  
  67. // Position Bar
  68. positionBar.setMax(totalTime);
  69. positionBar.setOnSeekBarChangeListener(
  70. new SeekBar.OnSeekBarChangeListener() {
  71. @Override
  72. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  73. if (fromUser) {
  74. mp.seekTo(progress);
  75. positionBar.setProgress(progress);
  76. }
  77. }
  78.  
  79. @Override
  80. public void onStartTrackingTouch(SeekBar seekBar) {
  81.  
  82. }
  83.  
  84. @Override
  85. public void onStopTrackingTouch(SeekBar seekBar) {
  86.  
  87. }
  88. }
  89. );
  90.  
  91.  
  92. // Volume Bar
  93. volumeBar.setOnSeekBarChangeListener(
  94. new SeekBar.OnSeekBarChangeListener() {
  95. @Override
  96. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  97. float volumeNum = progress / 100f;
  98. mp.setVolume(volumeNum, volumeNum);
  99. }
  100.  
  101. @Override
  102. public void onStartTrackingTouch(SeekBar seekBar) {
  103.  
  104. }
  105.  
  106. @Override
  107. public void onStopTrackingTouch(SeekBar seekBar) {
  108.  
  109. }
  110. }
  111. );
  112.  
  113. // Thread (Update positionBar & timeLabel)
  114. new Thread(new Runnable() {
  115. @Override
  116. public void run() {
  117. while (mp != null) {
  118. try {
  119. Message msg = new Message();
  120. msg.what = mp.getCurrentPosition();
  121. handler.sendMessage(msg);
  122. Thread.sleep(1000);
  123. } catch (InterruptedException e) {
  124. }
  125. }
  126. }
  127. }).start();
  128.  
  129. //spinner
  130.  
  131. dropdown = (Spinner) findViewById(R.id.spinner1);
  132. ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
  133. dropdown.setAdapter(adapter);
  134. dropdown.setSelection(0, false);
  135. dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  136. @Override
  137. public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  138. Log.d("listener", "wybrano obiekt " + id);
  139. // Media Player
  140. mp.stop();
  141. mp.release();
  142. mp = null;
  143. playBtn.setBackgroundResource(R.drawable.play);
  144. mp = MediaPlayer.create(getApplicationContext(), Uri.parse("android.resource://com.example.lab6/raw/" + items[(int) id]));
  145. mp.setLooping(true);
  146. mp.seekTo(0);
  147. mp.setVolume(0.5f, 0.5f);
  148. totalTime = mp.getDuration();
  149.  
  150. // Position Bar
  151. positionBar.setMax(totalTime);
  152.  
  153. mVisualizer.release();
  154. mVisualizer = null;
  155. mVisualizerView = null;
  156.  
  157. mVisualizerView = (VisualizerView) findViewById(R.id.myvisualizerview);
  158. initAudio();
  159.  
  160. }
  161.  
  162. @Override
  163. public void onNothingSelected(AdapterView<?> parent) {
  164.  
  165. }
  166. });
  167.  
  168. mVisualizerView = (VisualizerView) findViewById(R.id.myvisualizerview);
  169. initAudio();
  170.  
  171. //Recorder
  172.  
  173.  
  174. play = (Button) findViewById(R.id.play);
  175. stop = (Button) findViewById(R.id.stop);
  176. record = (Button) findViewById(R.id.record);
  177. stop.setEnabled(false);
  178. play.setEnabled(false);
  179. outputFile = getExternalFilesDir(null) + "/recording.mp3";
  180. myAudioRecorder = new MediaRecorder();
  181. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
  182. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
  183. != PackageManager.PERMISSION_GRANTED) {
  184. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},
  185. 10);
  186. }
  187. }
  188. myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  189. myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
  190. myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.MPEG_4);
  191. myAudioRecorder.setOutputFile(outputFile);
  192.  
  193. record.setOnClickListener(new View.OnClickListener() {
  194. @Override
  195. public void onClick(View v) {
  196. if (myAudioRecorder == null) {
  197. myAudioRecorder = new MediaRecorder();
  198. myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  199. myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
  200. myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.MPEG_4);
  201. myAudioRecorder.setOutputFile(outputFile);
  202. }
  203. try {
  204. myAudioRecorder.prepare();
  205. myAudioRecorder.start();
  206. } catch (IllegalStateException ise) {
  207. Log.e("Record ERROR ise", "error");
  208. } catch (IOException ioe) {
  209. Log.e("Record ERROR ioe", "error");
  210. }
  211. record.setEnabled(false);
  212. stop.setEnabled(true);
  213. Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
  214. }
  215. });
  216.  
  217. stop.setOnClickListener(new View.OnClickListener() {
  218. @Override
  219. public void onClick(View v) {
  220. try {
  221. myAudioRecorder.stop();
  222. } catch (RuntimeException e) {
  223. Log.e("Stop recording ERROR", "error");
  224. } finally {
  225. myAudioRecorder.release();
  226. myAudioRecorder = null;
  227. }
  228. record.setEnabled(true);
  229. stop.setEnabled(false);
  230. play.setEnabled(true);
  231. Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
  232. }
  233. });
  234.  
  235. play.setOnClickListener(new View.OnClickListener() {
  236. @Override
  237. public void onClick(View v) {
  238. MediaPlayer mediaPlayer = new MediaPlayer();
  239. try {
  240. mediaPlayer.setDataSource(outputFile);
  241. mediaPlayer.prepare();
  242. mediaPlayer.start();
  243. Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show();
  244. } catch (Exception e) {
  245. Log.e("Play ERROR", "error playing recorded song");
  246. }
  247. }
  248. });
  249. Log.d("Path to output file:", outputFile);
  250. }
  251.  
  252. @Override
  253. protected void onPause() {
  254. super.onPause();
  255. if (isFinishing() && mp != null) {
  256. mVisualizer.release();
  257. mp.release();
  258. mp = null;
  259. myAudioRecorder.release();
  260. myAudioRecorder = null;
  261. }
  262. }
  263.  
  264. private Handler handler = new Handler() {
  265. @Override
  266. public void handleMessage(Message msg) {
  267. int currentPosition = msg.what;
  268. // Update positionBar.
  269. positionBar.setProgress(currentPosition);
  270.  
  271. // Update Labels.
  272. String elapsedTime = createTimeLabel(currentPosition);
  273. elapsedTimeLabel.setText(elapsedTime);
  274.  
  275. String remainingTime = createTimeLabel(totalTime - currentPosition);
  276. remainingTimeLabel.setText("- " + remainingTime);
  277. }
  278. };
  279.  
  280. public String createTimeLabel(int time) {
  281. String timeLabel = "";
  282. int min = time / 1000 / 60;
  283. int sec = time / 1000 % 60;
  284.  
  285. timeLabel = min + ":";
  286. if (sec < 10) timeLabel += "0";
  287. timeLabel += sec;
  288.  
  289. return timeLabel;
  290. }
  291.  
  292. public void playBtnClick(View view) {
  293.  
  294. if (!mp.isPlaying()) {
  295. // Stopping
  296. mp.start();
  297. playBtn.setBackgroundResource(R.drawable.stop);
  298.  
  299. } else {
  300. // Playing
  301. mp.pause();
  302. playBtn.setBackgroundResource(R.drawable.play);
  303. }
  304.  
  305. }
  306.  
  307. private void initAudio() {
  308. setVolumeControlStream(AudioManager.STREAM_MUSIC);
  309.  
  310. setupVisualizerFxAndUI();
  311. // Make sure the visualizer is enabled only when you actually want to
  312. // receive data, and
  313. // when it makes sense to receive data.
  314. mVisualizer.setEnabled(true);
  315. // When the stream ends, we don't need to collect any more data. We
  316. // don't do this in
  317. // setupVisualizerFxAndUI because we likely want to have more,
  318. // non-Visualizer related code
  319. // in this callback.
  320. mp
  321. .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  322. public void onCompletion(MediaPlayer mediaPlayer) {
  323. mVisualizer.setEnabled(false);
  324. }
  325. });
  326. }
  327.  
  328. private void setupVisualizerFxAndUI() {
  329.  
  330. // Create the Visualizer object and attach it to our media player.
  331. mVisualizer = new Visualizer(mp.getAudioSessionId());
  332. mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
  333. mVisualizer.setDataCaptureListener(
  334. new Visualizer.OnDataCaptureListener() {
  335. public void onWaveFormDataCapture(Visualizer visualizer,
  336. byte[] bytes, int samplingRate) {
  337. mVisualizerView.updateVisualizer(bytes);
  338. }
  339.  
  340. public void onFftDataCapture(Visualizer visualizer,
  341. byte[] bytes, int samplingRate) {
  342. }
  343. }, Visualizer.getMaxCaptureRate() / 2, true, false);
  344. }
  345. }
  346.  
  347. -------------------------------------------------------
  348. //VisualView
  349.  
  350.  
  351. package com.example.media;
  352.  
  353. import android.content.Context;
  354. import android.graphics.Canvas;
  355. import android.graphics.Color;
  356. import android.graphics.Paint;
  357. import android.graphics.Rect;
  358. import android.util.AttributeSet;
  359. import android.view.View;
  360.  
  361. public class VisualizerView extends View {
  362.  
  363. private byte[] mBytes;
  364. private float[] mPoints;
  365. private Rect mRect = new Rect();
  366. private Paint mForePaint = new Paint();
  367.  
  368. public VisualizerView(Context context) {
  369. super(context);
  370. init();
  371. }
  372.  
  373. public VisualizerView(Context context, AttributeSet attrs) {
  374. super(context, attrs);
  375. init();
  376. }
  377.  
  378. public VisualizerView(Context context, AttributeSet attrs, int defStyleAttr) {
  379. super(context, attrs, defStyleAttr);
  380. init();
  381. }
  382.  
  383. private void init() {
  384. mBytes = null;
  385. mForePaint.setStrokeWidth(1f);
  386. mForePaint.setAntiAlias(true);
  387. mForePaint.setColor(Color.rgb(0, 128, 255));
  388. }
  389.  
  390. public void updateVisualizer(byte[] bytes) {
  391. mBytes = bytes;
  392. invalidate();
  393. }
  394.  
  395. @Override
  396. protected void onDraw(Canvas canvas) {
  397. super.onDraw(canvas);
  398. if (mBytes == null) {
  399. return;
  400. }
  401. if (mPoints == null || mPoints.length < mBytes.length * 4) {
  402. mPoints = new float[mBytes.length * 4];
  403. }
  404. mRect.set(0, 0, getWidth(), getHeight());
  405. for (int i = 0; i < mBytes.length - 1; i++) {
  406. mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
  407. mPoints[i * 4 + 1] = mRect.height() / 2
  408. + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
  409. mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
  410. mPoints[i * 4 + 3] = mRect.height() / 2
  411. + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2)
  412. / 128;
  413. }
  414. canvas.drawLines(mPoints, mForePaint);
  415. }
  416.  
  417. }
  418.  
  419. -----------------------------------------------------------------------------------------------
  420.  
  421. // Manifest
  422. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  423. <uses-permission android:name="android.permission.RECORD_AUDIO" />
  424.  
  425.  
  426. -----------------------------------------------------------------------------------------------------
  427.  
  428. XML layout
  429.  
  430.  
  431. <?xml version="1.0" encoding="utf-8"?>
  432.  
  433. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lab6.MainActivity" android:orientation="vertical" android:gravity="center_horizontal">
  434. <Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content"/>
  435. <SeekBar android:id="@+id/positionBar" android:layout_width="300dp" android:layout_height="wrap_content" android:layout_marginTop="30dp"/>
  436. <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content">
  437. <TextView android:id="@+id/elapsedTimeLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0:11" android:layout_marginLeft="40dp"/>
  438. <TextView android:id="@+id/remainingTimeLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-1:49" android:layout_marginLeft="240dp"/>
  439. </LinearLayout>
  440. <Button android:id="@+id/playBtn" android:layout_width="30dp" android:layout_height="30dp" android:background="@drawable/play" android:layout_marginTop="40dp" android:onClick="playBtnClick"/>
  441. <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="40dp" android:gravity="center">
  442. <ImageView android:layout_width="18dp" android:layout_height="18dp" android:src="@drawable/sound1"/>
  443. <SeekBar android:id="@+id/volumeBar" android:layout_width="300dp" android:layout_height="wrap_content" android:progress="50" android:max="100"/>
  444. <ImageView android:layout_width="26dp" android:layout_height="26dp" android:src="@drawable/sound2"/>
  445. </LinearLayout>
  446. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Record" android:textSize="20sp" android:id="@+id/record" android:layout_centerHorizontal="true" android:layout_marginTop="15dp"/>
  447. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:textSize="20sp" android:id="@+id/stop" android:layout_below="@id/record" android:layout_marginTop="10dp" android:layout_centerHorizontal="true"/>
  448. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play" android:textSize="20sp" android:id="@+id/play" android:layout_below="@id/stop" android:layout_marginTop="10dp" android:layout_centerHorizontal="true"/>
  449. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.androidaudiovisualizer.MainActivity">
  450. <com.example.lab6.VisualizerView android:id="@+id/myvisualizerview" android:layout_width="match_parent" android:layout_height="match_parent"/>
  451. </LinearLayout>
  452. </LinearLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement