Skip to main content

Working with Audio and Video Playback

1. Playing Audio Files

Property Description Values
source URI or resource ID of the audio file string
volume Volume level (0.0 to 1.0) number
rate Playback rate (1.0 = normal speed) number
paused Whether to pause playback boolean
muted Whether to mute the audio boolean
controls Whether to show default controls boolean

Example: Basic Audio Playback

<Audio
  source="https://example.com/audio.mp3"
  volume={1.0}
  rate={1.0}
  paused={false}
  muted={false}
  controls={true}
/>
Note: On iOS, audio files must be included in the app bundle or downloaded to a local file path.
Warning: On Android, audio playback requires the RECORD_AUDIO permission in AndroidManifest.xml.
Event Description Parameters
onLoad Fired when audio is loaded duration, currentTime
onPlay Fired when playback starts currentTime
onPause Fired when playback is paused currentTime
onEnd Fired when playback ends currentTime

Example: Handling Audio Events

const handlePlay = () => {
  console.log("Audio started");
};

const handleEnd = () => {
  console.log("Audio finished");
};

<Audio
  source="https://example.com/audio.mp3"
  onPlay={handlePlay}
  onEnd={handleEnd}
/>

2. Recording Audio

Property Description Notes
recorder Instance of audio recorder Used to manage recording sessions
audioSource Source of audio input (e.g., microphone) Can be set to different input sources
format Audio format (e.g., WAV, MP3) Determines file type and compression
sampleRate Audio sample rate in Hz (e.g., 44100) Higher rates provide better quality
bitRate Audio bit rate in bps (e.g., 128000) Higher bit rates improve quality

Example: Start Recording Audio

import { Audio } from 'expo-av';

const startRecording = async () => {
  try {
    await Audio.requestPermissionsAsync();
    const { status } = await Audio.getPermissionsAsync();
    
    if (status !== 'granted') {
      console.warn('Permission to access audio was denied');
      return;
    }

    const recording = new Audio.Recording();
    await recording.prepareToRecordAsync(Audio.RECORDING_OPTIONS);
    await recording.startAsync();
    
    console.log('Recording started');
  } catch (error) {
    console.error('Error starting recording:', error);
  }
};

Example: Stop Recording Audio

const stopRecording = async () => {
  try {
    await recording.stopAndSaveAsync();
    console.log('Recording stopped and saved');
  } catch (error) {
    console.error('Error stopping recording:', error);
  }
};
Note: Ensure that the app has proper permissions to access the microphone before attempting to record audio.
Warning: Recording audio may require additional permissions depending on the platform (iOS/Android).

3. Implementing Audio Controls

Property Description Values
controls Displays default audio controls true or false
src URL of the audio file string
autoPlay Starts playing the audio automatically true or false
loop Repeats the audio when finished true or false
muted Starts the audio muted true or false

Example: Basic Audio Player

<Audio
  src="https://example.com/audio.mp3"
  controls={true}
  autoPlay={false}
  loop={false}
  muted={false}
/>

Example: Custom Audio Controls

import { useState } from &#x27;react&#x27;;
import { TouchableOpacity, Text } from &#x27;react-native&#x27;;

const AudioPlayer = () => {
  const [isPlaying, setIsPlaying] = useState(false);

  const togglePlay = () => {
    setIsPlaying(!isPlaying);
  };

  return (
    <TouchableOpacity onPress={togglePlay}>
      <Text>{isPlaying ? &#x27;Pause&#x27; : &#x27;Play&#x27;}</Text>
    </TouchableOpacity>
  );
};
Note: For advanced audio control, consider using react-native-track-player for more granular control over playback.

4. Managing Audio Sessions

Property Description Values
audioMode Sets the audio session mode 'ambient', 'playback', 'record', 'mixWithOthers'
category Defines the audio session category 'playback', 'record', 'ambient', 'playAndRecord'
active Indicates if the session is active true, false

Example: Setting Audio Mode

import { Audio } from 'expo-av';

Audio.setAudioModeAsync({
  android: {
    mode: 'playback',
    mixWithOthers: true,
  },
  ios: {
    mode: 'playback',
    mixWithOthers: true,
  }
});
Note: On iOS, setting mixWithOthers to true allows other audio to play simultaneously.
Warning: On Android, mode must be one of 'ambient', 'playback', or 'record'.

5. Implementing Background Audio Playback

Example: Setting up Background Audio with react-native-audio-toolkit

import { AudioRecorder, AudioUtils } from 'react-native-audio-toolkit';

const audioFile = AudioUtils.DocumentDirectoryPath + '/recording.m4a';

AudioRecorder.prepareRecordingAtPath(audioFile, {
  SampleRate: 22050,
  Channels: 1,
  AudioQuality: 'Low',
  AudioEncoding: 'aac',
});

AudioRecorder.startRecording();
Property Description Default Value Notes
SampleRate Audio sample rate in Hz 44100 Higher rates improve quality but increase file size
Channels Number of audio channels (1 = mono, 2 = stereo) 2 Use 1 for voice recordings
AudioQuality Quality level of the recording Medium Options: Low, Medium, High
AudioEncoding Format of the recorded file mp4 Supported: aac, mp4
Note: For background audio playback, ensure your app has the necessary permissions in AndroidManifest.xml and Info.plist.
Warning: On iOS, background audio requires UIBackgroundModes set to audio in your app's Info.plist.

Key Steps for Background Audio Playback

  • Configure audio session with AVAudioSessionCategoryPlayback
  • Set up background mode in app capabilities
  • Use react-native-audio-toolkit or expo-av for playback
  • Handle interruptions (e.g., phone calls) gracefully

6. Using react-native-video Component

Example: Basic Video Player

{`import React from 'react';
import { View } from 'react-native';
import Video from 'react-native-video';

const VideoPlayer = () => {
  return (
    <View style={{ flex: 1 }}>
      <Video
        source={{ uri: 'https://example.com/video.mp4' }}
        style={{ width: '100%', height: 300 }}
        controls={true}
        resizeMode="contain"
      />
    </View>
  );
};

export default VideoPlayer;`}
Property Type Description Default
source object Video source object with uri or asset null
style object Styles for the video component {}
controls boolean Show native controls (play/pause, volume) false
paused boolean Pause or resume playback false
resizeMode string How to scale video: contain, cover, stretch contain
volume number Volume level (0.0 to 1.0) 1.0
muted boolean Mute or unmute audio false
playbackRate number Playback speed (0.25 to 4.0) 1.0
onLoad function Called when video metadata is loaded null
onProgress function Called periodically with progress info null
onEnd function Called when video finishes playing null
onError function Called when an error occurs null
Note: The react-native-video component supports both local and remote video sources. For iOS, you may need to configure NSAppTransportSecurity in your Info.plist for remote URLs.

Example: Video with Custom Controls

{`import React, { useState } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import Video from 'react-native-video';

const CustomVideoPlayer = () => {
  const [paused, setPaused] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);

  return (
    <View style={{ flex: 1 }}>
      <Video
        source={{ uri: 'https://example.com/video.mp4' }}
        style={{ width: '100%', height: 300 }}
        paused={paused}
        onProgress={(data) => setCurrentTime(data.currentTime)}
        controls={false}
      />
      <TouchableOpacity
        onPress={() => setPaused(!paused)}
        style={{ padding: 10, backgroundColor: '#007AFF' }}
      >
        <Text style={{ color: 'white' }}>
          {paused ? 'Play' : 'Pause'}
        </Text>
      </TouchableOpacity>
    </View>
  );
};

export default CustomVideoPlayer;`}

7. Implementing Video Controls

Example: Basic Video Player with Custom Controls

import React, { useState } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import { Video } from 'expo-av';

const VideoPlayer = () => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  const handlePlayPause = () => {
    setIsPlaying(!isPlaying);
  };

  const handleProgress = (data) => {
    setCurrentTime(data.currentTime);
  };

  const handleLoad = (data) => {
    setDuration(data.duration);
  };

  return (
    <View style={styles.container}>
      <Video
        source={{ uri: 'https://example.com/video.mp4' }}
        style={styles.video}
        paused={!isPlaying}
        onProgress={handleProgress}
        onLoad={handleLoad}
      />
      <View style={styles.controls}>
        <TouchableOpacity onPress={handlePlayPause} style={styles.button}>
          <Text style={styles.buttonText}>
            {isPlaying ? 'Pause' : 'Play'}
          </Text>
        </TouchableOpacity>
        <Text style={styles.time}>
          {Math.floor(currentTime / 60)}:{String(Math.floor(currentTime % 60)).padStart(2, '0')}
        </Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  video: {
    width: '100%',
    height: 300,
  },
  controls: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 10,
  },
  button: {
    backgroundColor: '#007AFF',
    padding: 10,
    borderRadius: 5,
    marginRight: 10,
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
  },
  time: {
    fontSize: 14,
    color: '#000',
  },
});

export default VideoPlayer;
Property Description Values
paused Controls whether the video is paused or playing true / false
onProgress Callback when video progress updates Function with currentTime
onLoad Callback when video metadata is loaded Function with duration
Note: The expo-av package is required for video playback in React Native.
Warning: Video controls must be implemented carefully to avoid UI blocking or performance issues.

8. Handling Fullscreen Video

Property Description Values
fullscreen Controls whether the video should be displayed in fullscreen mode true or false

Example: Toggle fullscreen mode

import React, { useState } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import { Video } from 'expo-av';

const FullscreenVideoPlayer = () => {
  const [isFullscreen, setIsFullscreen] = useState(false);

  return (
    <View style={{ flex: 1 }}>
      <Video
        source={{ uri: 'https://example.com/video.mp4' }}
        style={{ width: '100%', height: 300 }}
        fullscreen={isFullscreen}
        controls={true}
      />
      <TouchableOpacity
        onPress={() => setIsFullscreen(!isFullscreen)}
        style={{ padding: 10, backgroundColor: '#007AFF', marginTop: 10 }}
      >
        <Text style={{ color: 'white' }}>
          {isFullscreen ? 'Exit Fullscreen' : 'Enter Fullscreen'}
        </Text>
      </TouchableOpacity>
    </View>
  );
};

export default FullscreenVideoPlayer;
Note: The fullscreen property is supported in expo-av and requires appropriate permissions for fullscreen mode on mobile devices.

9. Streaming Live Audio and Video

Property Description Values
source URL or local file path to the live stream string
controls Whether to show default controls true | false
paused Whether the stream is paused true | false
volume Volume level (0.0 to 1.0) number

Example: Streaming Live Video

import React from 'react';
import { Video } from 'react-native-video';

const LiveVideoStream = () => {
  return (
    <Video
      source={{ uri: 'https://example.com/live.m3u8' }}
      controls={true}
      paused={false}
      volume={1.0}
      style={{ width: 300, height: 200 }}
    />
  );
};

export default LiveVideoStream;
Note: Live streams often require HLS or DASH formats for compatibility across platforms.
Warning: Ensure proper network permissions and handle buffering states for live streams.

10. Implementing Audio Focus Handling

Property Description Values
onAudioFocusChange Callback function when audio focus changes function(focus: boolean)
audioMode Audio session mode configuration 'ambient' | 'playback' | 'record' | 'mixWithOthers'

Example: Setting Audio Mode

import { Audio } from 'expo-av';

Audio.setAudioModeAsync({
  playsInSilentModeIOS: true,
  shouldDuckAndroid: true,
  audioMode: 'playback'
});

Example: Handling Focus Change

import { Audio } from 'expo-av';

const handleFocusChange = (hasFocus) => {
  if (hasFocus) {
    // Resume playback
    sound.playAsync();
  } else {
    // Pause playback
    sound.pauseAsync();
  }
};

Audio.setAudioModeAsync({
  onAudioFocusChange: handleFocusChange
});
Note: On Android, shouldDuckAndroid controls whether audio ducks (lowers volume) when another app requests focus.

Was this article helpful?