17 |
18 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx512m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/codility/voicerecorder/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.codility.voicerecorder
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("com.codility.voicerecorder", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 AndroidCodility
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Voice Recorder
2 | Android application to record their voice or any other sound for that matter and the recording gets stored locally and can be listened to any time in the future as per the requirement using Kotlin Programming Language.
3 |
4 | [Audio Recorder](https://developer.android.com/reference/android/media/AudioRecord.html) is application, which makes it easy to record and playback audio on your smartphone or tablet.
5 |
6 | VOICE 1 | VOICE 2 | VOICE 3 |
7 | :---------:|:----------:|:---------:
8 |  |  | 
9 |
10 | # Play Video
11 | [](https://youtu.be/FHWrPUrUhjI "Click here to watch")
12 |
13 | # Like Facebook Page
14 | [](https://www.facebook.com/androidcodility/ "Click here")
15 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | android {
8 | compileSdkVersion 27
9 | defaultConfig {
10 | applicationId "com.codility.voicerecorder"
11 | minSdkVersion 15
12 | targetSdkVersion 27
13 | versionCode 1
14 | versionName "1.0"
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
28 | implementation 'com.android.support:appcompat-v7:27.1.0'
29 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
30 | implementation 'com.android.support:recyclerview-v7:27.1.0'
31 | testImplementation 'junit:junit:4.12'
32 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
33 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/record_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
17 |
18 |
25 |
26 |
34 |
35 |
39 |
40 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
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 | 1.8
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_recording.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
28 |
29 |
37 |
38 |
43 |
44 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/codility/voicerecorder/adapter/MyAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.codility.recyclerview
2 |
3 | import android.media.MediaPlayer
4 | import android.os.Build
5 | import android.os.Handler
6 | import android.support.annotation.RequiresApi
7 | import android.support.v7.widget.RecyclerView
8 | import android.transition.TransitionManager
9 | import android.view.LayoutInflater
10 | import android.view.View
11 | import android.view.ViewGroup
12 | import android.widget.ImageView
13 | import android.widget.SeekBar
14 | import android.widget.TextView
15 | import com.codility.voicerecorder.R
16 | import com.codility.voicerecorder.model.Recording
17 | import kotlinx.android.synthetic.main.item_recording.view.*
18 |
19 | /**
20 | * Created by Govind on 3/28/2018.
21 | */
22 |
23 | @RequiresApi(Build.VERSION_CODES.KITKAT)
24 | class MyAdapter(private val recordList: ArrayList) : RecyclerView.Adapter() {
25 |
26 | private var onClickListener: OnClickListener? = null
27 |
28 | fun setListener(onClickListener: OnClickListener) {
29 | this.onClickListener = onClickListener
30 | }
31 |
32 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
33 | return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_recording, parent, false))
34 | }
35 |
36 | override fun onBindViewHolder(holder: ViewHolder, position: Int) {
37 | holder.bindItems(recordList, onClickListener)
38 | }
39 |
40 | override fun getItemCount(): Int {
41 | return recordList.size
42 | }
43 |
44 | class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
45 | private var mediaPlayer: MediaPlayer? = null
46 | private var lastProgress = 0
47 | private val mHandler = Handler()
48 |
49 | fun bindItems(recordingList: ArrayList, onClickListener: OnClickListener?) {
50 | val recording: Recording = recordingList[adapterPosition]
51 | val tvRecordName = itemView.findViewById(R.id.tvRecordName)
52 | val imgViewPlay = itemView.findViewById(R.id.imgViewPlay)
53 | val seekBar = itemView.findViewById(R.id.seekBar)
54 | tvRecordName.text = recording.fileName
55 |
56 | if (recording.isPlaying) {
57 | imgViewPlay.setImageResource(R.drawable.ic_pause_circle)
58 | TransitionManager.beginDelayedTransition(itemView as ViewGroup)
59 | seekBar.visibility = View.VISIBLE
60 | seekUpdate(itemView)
61 | } else {
62 | imgViewPlay.setImageResource(R.drawable.ic_play_circle)
63 | TransitionManager.beginDelayedTransition(itemView as ViewGroup)
64 | seekBar.visibility = View.GONE
65 | }
66 |
67 | manageSeekBar(seekBar)
68 |
69 | imgViewPlay.setOnClickListener(View.OnClickListener {
70 | if (onClickListener != null) {
71 | onClickListener.onClickPlay(itemView, recording, recordingList, adapterPosition)
72 | }
73 | })
74 | }
75 |
76 | private fun manageSeekBar(seekBar: SeekBar?) {
77 | seekBar!!.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
78 | override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
79 | if (mediaPlayer != null && fromUser) {
80 | mediaPlayer!!.seekTo(progress)
81 | }
82 | }
83 |
84 | override fun onStartTrackingTouch(seekBar: SeekBar) {
85 |
86 | }
87 |
88 | override fun onStopTrackingTouch(seekBar: SeekBar) {
89 |
90 | }
91 | })
92 | }
93 |
94 | private var runnable: Runnable = Runnable { seekUpdate(itemView) }
95 |
96 | private fun seekUpdate(itemView: View) {
97 | if (mediaPlayer != null) {
98 | val mCurrentPosition = mediaPlayer!!.currentPosition
99 | itemView.seekBar.max = mediaPlayer!!.duration
100 | itemView.seekBar.progress = mCurrentPosition
101 | lastProgress = mCurrentPosition
102 | }
103 | mHandler.postDelayed(runnable, 100)
104 | }
105 | }
106 |
107 | interface OnClickListener {
108 | fun onClickPlay(view: View, record: Recording, recordingList: ArrayList, position: Int)
109 | }
110 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
16 |
17 |
26 |
27 |
33 |
34 |
42 |
43 |
51 |
52 |
60 |
61 |
69 |
70 |
76 |
77 |
78 |
79 |
85 |
86 |
93 |
94 |
102 |
103 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/codility/voicerecorder/RecordListActivity.kt:
--------------------------------------------------------------------------------
1 | package com.codility.voicerecorder
2 |
3 | import android.media.MediaPlayer
4 | import android.os.Build
5 | import android.os.Bundle
6 | import android.os.Handler
7 | import android.support.annotation.RequiresApi
8 | import android.support.v7.app.AppCompatActivity
9 | import android.support.v7.widget.LinearLayoutManager
10 | import android.util.Log
11 | import android.view.MenuItem
12 | import android.view.View
13 | import android.widget.SeekBar
14 | import com.codility.recyclerview.MyAdapter
15 | import com.codility.voicerecorder.model.Recording
16 | import kotlinx.android.synthetic.main.item_recording.view.*
17 | import kotlinx.android.synthetic.main.record_list.*
18 | import java.io.File
19 | import java.io.IOException
20 |
21 | /**
22 | * Created by Govind on 3/29/2018.
23 | */
24 | @RequiresApi(Build.VERSION_CODES.KITKAT)
25 | class RecordListActivity : AppCompatActivity(), MyAdapter.OnClickListener {
26 | private var mediaPlayer: MediaPlayer? = null
27 | private var lastProgress = 0
28 | private val mHandler = Handler()
29 | private var isPlaying = false
30 | private var last_index = -1
31 | private var myAdapter: MyAdapter? = null
32 |
33 | override fun onClickPlay(view: View, record: Recording, recordingList: ArrayList, position: Int) {
34 | playRecordItem(view, record, recordingList, position)
35 | }
36 |
37 | private fun playRecordItem(view: View, recordItem: Recording, recordingList: ArrayList, position: Int) {
38 | val recording = recordingList[position]
39 |
40 | if (isPlaying) {
41 | stopPlaying()
42 | if (position == last_index) {
43 | recording.isPlaying = false
44 | stopPlaying()
45 | myAdapter!!.notifyItemChanged(position)
46 | } else {
47 | markAllPaused(recordingList)
48 | recording.isPlaying = true
49 | myAdapter!!.notifyItemChanged(position)
50 | startPlaying(recording.uri, recordItem, view.seekBar, position)
51 | last_index = position
52 | }
53 | seekUpdate(view)
54 | } else {
55 | if (recording.isPlaying) {
56 | recording.isPlaying = false
57 | stopPlaying()
58 | } else {
59 | startPlaying(recording.uri, recordItem, view.seekBar, position)
60 | recording.isPlaying = true
61 | view.seekBar.max = mediaPlayer!!.duration
62 | }
63 | myAdapter!!.notifyItemChanged(position)
64 | last_index = position
65 | }
66 |
67 | manageSeekBar(view.seekBar)
68 | }
69 |
70 | override fun onCreate(savedInstanceState: Bundle?) {
71 | super.onCreate(savedInstanceState)
72 | setContentView(R.layout.record_list)
73 |
74 | supportActionBar!!.setDisplayHomeAsUpEnabled(true)
75 |
76 | getAllRecordings()
77 | }
78 |
79 | private fun getAllRecordings() {
80 | val recordArrayList = ArrayList()
81 | val root = android.os.Environment.getExternalStorageDirectory()
82 | val path = root.absolutePath + "/AndroidCodility/Audios"
83 | val directory = File(path)
84 | val files = directory.listFiles()
85 | if (files != null) {
86 |
87 | for (i in files.indices) {
88 | val fileName = files[i].name
89 | val recordingUri = root.absolutePath + "/AndroidCodility/Audios/" + fileName
90 | recordArrayList.add(Recording(recordingUri, fileName, false))
91 | }
92 | tvNoData.visibility = View.GONE
93 | recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
94 | myAdapter = MyAdapter(recordArrayList)
95 | myAdapter!!.setListener(this)
96 | recyclerView.adapter = myAdapter
97 | }
98 | }
99 |
100 | override fun onOptionsItemSelected(item: MenuItem?): Boolean {
101 | if (item!!.itemId == android.R.id.home) {
102 | finish()
103 | }
104 | return super.onOptionsItemSelected(item)
105 | }
106 |
107 | private fun seekUpdate(itemView: View) {
108 | if (mediaPlayer != null) {
109 | val mCurrentPosition = mediaPlayer!!.currentPosition
110 | itemView.seekBar.max = mediaPlayer!!.duration
111 | itemView.seekBar.progress = mCurrentPosition
112 | lastProgress = mCurrentPosition
113 | }
114 | mHandler.postDelayed(Runnable { seekUpdate(itemView) }, 100)
115 | }
116 |
117 | private fun manageSeekBar(seekBar: SeekBar?) {
118 | seekBar!!.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
119 | override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
120 | if (mediaPlayer != null && fromUser) {
121 | mediaPlayer!!.seekTo(progress)
122 | }
123 | }
124 |
125 | override fun onStartTrackingTouch(seekBar: SeekBar) {}
126 |
127 | override fun onStopTrackingTouch(seekBar: SeekBar) {}
128 | })
129 | }
130 |
131 | private fun stopPlaying() {
132 | try {
133 | mediaPlayer!!.release()
134 | } catch (e: Exception) {
135 | e.printStackTrace()
136 | }
137 |
138 | mediaPlayer = null
139 | isPlaying = false
140 | }
141 |
142 | private fun startPlaying(uri: String?, audio: Recording?, seekBar: SeekBar?, position: Int) {
143 | mediaPlayer = MediaPlayer()
144 | try {
145 | mediaPlayer!!.setDataSource(uri)
146 | mediaPlayer!!.prepare()
147 | mediaPlayer!!.start()
148 | } catch (e: IOException) {
149 | Log.e("LOG_TAG", "prepare() failed")
150 | }
151 | //showing the pause button
152 | seekBar!!.max = mediaPlayer!!.duration
153 | isPlaying = true
154 |
155 | mediaPlayer!!.setOnCompletionListener(MediaPlayer.OnCompletionListener {
156 | audio!!.isPlaying = false
157 | myAdapter!!.notifyItemChanged(position)
158 | })
159 | }
160 |
161 | private fun markAllPaused(recordingList: ArrayList) {
162 | for (i in recordingList.indices) {
163 | recordingList[i].isPlaying = false
164 | recordingList[i] = recordingList[i]
165 | }
166 | myAdapter!!.notifyDataSetChanged()
167 | }
168 |
169 | override fun onBackPressed() {
170 | super.onBackPressed()
171 | stopPlaying()
172 | }
173 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/codility/voicerecorder/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.codility.voicerecorder
2 |
3 | import android.Manifest
4 | import android.content.Intent
5 | import android.content.pm.PackageManager
6 | import android.media.MediaPlayer
7 | import android.media.MediaRecorder
8 | import android.os.Build
9 | import android.os.Bundle
10 | import android.os.Handler
11 | import android.os.SystemClock
12 | import android.support.annotation.RequiresApi
13 | import android.support.v4.content.ContextCompat
14 | import android.support.v7.app.AppCompatActivity
15 | import android.transition.TransitionManager
16 | import android.util.Log
17 | import android.view.View
18 | import android.widget.SeekBar
19 | import android.widget.Toast
20 | import kotlinx.android.synthetic.main.activity_main.*
21 | import java.io.File
22 | import java.io.IOException
23 |
24 | @RequiresApi(api = Build.VERSION_CODES.M)
25 | class MainActivity : AppCompatActivity(), View.OnClickListener {
26 |
27 | private var mRecorder: MediaRecorder? = null
28 | private var mPlayer: MediaPlayer? = null
29 | private var fileName: String? = null
30 | private var lastProgress = 0
31 | private val mHandler = Handler()
32 | private val RECORD_AUDIO_REQUEST_CODE = 101
33 | private var isPlaying = false
34 |
35 | override fun onClick(view: View?) {
36 | when (view!!.id) {
37 | R.id.imgBtRecord -> {
38 | prepareRecording()
39 | startRecording()
40 | }
41 |
42 | R.id.imgBtStop -> {
43 | prepareStop()
44 | stopRecording()
45 | }
46 |
47 | R.id.imgViewPlay -> {
48 | if (!isPlaying && fileName != null) {
49 | isPlaying = true
50 | startPlaying()
51 | } else {
52 | isPlaying = false
53 | stopPlaying()
54 | }
55 | }
56 |
57 | R.id.imgBtRecordList -> {
58 | startActivity(Intent(this, RecordListActivity::class.java))
59 | }
60 | }
61 | }
62 |
63 | override fun onCreate(savedInstanceState: Bundle?) {
64 | super.onCreate(savedInstanceState)
65 | setContentView(R.layout.activity_main)
66 |
67 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
68 | getPermissionToRecordAudio()
69 | }
70 |
71 | imgBtRecord.setOnClickListener(this)
72 | imgBtStop.setOnClickListener(this)
73 | imgViewPlay.setOnClickListener(this)
74 | imgBtRecordList.setOnClickListener(this)
75 | }
76 |
77 | private fun prepareStop() {
78 | TransitionManager.beginDelayedTransition(llRecorder)
79 | imgBtRecord.visibility = View.VISIBLE
80 | imgBtStop.visibility = View.GONE
81 | llPlay.visibility = View.VISIBLE
82 | }
83 |
84 |
85 | private fun prepareRecording() {
86 | TransitionManager.beginDelayedTransition(llRecorder)
87 | imgBtRecord.visibility = View.GONE
88 | imgBtStop.visibility = View.VISIBLE
89 | llPlay.visibility = View.GONE
90 | }
91 |
92 | private fun stopPlaying() {
93 | try {
94 | mPlayer!!.release()
95 | } catch (e: Exception) {
96 | e.printStackTrace()
97 | }
98 |
99 | mPlayer = null
100 | //showing the play button
101 | imgViewPlay.setImageResource(R.drawable.ic_play_circle)
102 | chronometer.stop()
103 | }
104 |
105 | private fun startRecording() {
106 | mRecorder = MediaRecorder()
107 | mRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
108 | mRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
109 | val root = android.os.Environment.getExternalStorageDirectory()
110 | val file = File(root.absolutePath + "/AndroidCodility/Audios")
111 | if (!file.exists()) {
112 | file.mkdirs()
113 | }
114 |
115 | fileName = root.absolutePath + "/AndroidCodility/Audios/" + (System.currentTimeMillis().toString() + ".mp3")
116 | Log.d("filename", fileName)
117 | mRecorder!!.setOutputFile(fileName)
118 | mRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
119 |
120 | try {
121 | mRecorder!!.prepare()
122 | mRecorder!!.start()
123 | } catch (e: IOException) {
124 | e.printStackTrace()
125 | }
126 |
127 | lastProgress = 0
128 | seekBar.progress = 0
129 | stopPlaying()
130 | // making the imageView a stop button starting the chronometer
131 | chronometer.base = SystemClock.elapsedRealtime()
132 | chronometer.start()
133 | }
134 |
135 |
136 | private fun stopRecording() {
137 | try {
138 | mRecorder!!.stop()
139 | mRecorder!!.release()
140 | } catch (e: Exception) {
141 | e.printStackTrace()
142 | }
143 | mRecorder = null
144 | //starting the chronometer
145 | chronometer.stop()
146 | chronometer.base = SystemClock.elapsedRealtime()
147 | //showing the play button
148 | Toast.makeText(this, "Recording saved successfully.", Toast.LENGTH_SHORT).show()
149 | }
150 |
151 |
152 | private fun startPlaying() {
153 | mPlayer = MediaPlayer()
154 | try {
155 | mPlayer!!.setDataSource(fileName)
156 | mPlayer!!.prepare()
157 | mPlayer!!.start()
158 | } catch (e: IOException) {
159 | Log.e("LOG_TAG", "prepare() failed")
160 | }
161 |
162 | //making the imageView pause button
163 | imgViewPlay.setImageResource(R.drawable.ic_pause_circle)
164 |
165 | seekBar.progress = lastProgress
166 | mPlayer!!.seekTo(lastProgress)
167 | seekBar.max = mPlayer!!.duration
168 | seekBarUpdate()
169 | chronometer.start()
170 |
171 | mPlayer!!.setOnCompletionListener(MediaPlayer.OnCompletionListener {
172 | imgViewPlay.setImageResource(R.drawable.ic_play_circle)
173 | isPlaying = false
174 | chronometer.stop()
175 | chronometer.base = SystemClock.elapsedRealtime()
176 | mPlayer!!.seekTo(0)
177 | })
178 |
179 | seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
180 | override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
181 | if (mPlayer != null && fromUser) {
182 | mPlayer!!.seekTo(progress)
183 | chronometer.base = SystemClock.elapsedRealtime() - mPlayer!!.currentPosition
184 | lastProgress = progress
185 | }
186 | }
187 |
188 | override fun onStartTrackingTouch(seekBar: SeekBar) {}
189 |
190 | override fun onStopTrackingTouch(seekBar: SeekBar) {}
191 | })
192 | }
193 |
194 | private var runnable: Runnable = Runnable { seekBarUpdate() }
195 |
196 | private fun seekBarUpdate() {
197 | if (mPlayer != null) {
198 | val mCurrentPosition = mPlayer!!.currentPosition
199 | seekBar.progress = mCurrentPosition
200 | lastProgress = mCurrentPosition
201 | }
202 | mHandler.postDelayed(runnable, 100)
203 | }
204 |
205 |
206 | private fun getPermissionToRecordAudio() {
207 | // 1) Use the support library version ContextCompat.checkSelfPermission(...) to avoid checking the build version since Context.checkSelfPermission(...) is only available in Marshmallow
208 | // 2) Always check for permission (even if permission has already been granted) since the user can revoke permissions at any time through Settings
209 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
210 | || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
211 | || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
212 | requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE), RECORD_AUDIO_REQUEST_CODE)
213 | }
214 | }
215 |
216 | // Callback with the request from calling requestPermissions(...)
217 | override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
218 | // Make sure it's our original READ_CONTACTS request
219 | if (requestCode == RECORD_AUDIO_REQUEST_CODE) {
220 | if (grantResults.size == 3 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
221 | //Toast.makeText(this, "Record Audio permission granted", Toast.LENGTH_SHORT).show();
222 | } else {
223 | Toast.makeText(this, "You must give permissions to use this app. App is exiting.", Toast.LENGTH_SHORT).show()
224 | finishAffinity()
225 | }
226 | }
227 | }
228 | }
--------------------------------------------------------------------------------