Media Playback

Back

Loading concept...

🎬 Media Playback in React Native

Video Player & Audio Player - Your App’s Entertainment Center!


The Big Picture: Your App as a Music Box & TV

Imagine your phone is like a magical box. Inside this box, you can:

  • Watch videos (like having a tiny TV in your pocket! 📺)
  • Listen to music (like having a personal radio! 🎵)

React Native lets you build this magic into your own apps. Let’s discover how!


🎭 The Universal Analogy: The Orchestra Conductor

Think of media playback like being a conductor of an orchestra:

  • 🎼 You (the app) = The Conductor
  • 🎻 Media files (video/audio) = The Musicians
  • 🎵 Play, Pause, Stop = Your hand signals
  • 👂 The user = The audience

Just like a conductor controls when music starts, stops, and how loud it plays—your app controls videos and audio the same way!


📺 Part 1: Video Player

What is a Video Player?

A video player is like a window to another world. It shows moving pictures with sound. Like when you watch cartoons!

The Simple Truth

To play videos in React Native, we use a special helper called react-native-video.

Installation

npm install react-native-video

Basic Video Player Example

import Video from 'react-native-video';

function MyVideoPlayer() {
  return (
    <Video
      source={{uri: 'https://example.com/movie.mp4'}}
      style={{width: 300, height: 200}}
      controls={true}
    />
  );
}

Breaking It Down (Like Building Blocks!)

Part What It Does Real-Life Example
source Where the video lives Like an address to your friend’s house
style How big the TV screen is Small TV vs Big TV
controls Play/Pause buttons Remote control!

🎮 Video Player Controls

Think of controls like buttons on a remote:

graph TD A["▶️ PLAY"] --> B["Video Starts"] C["⏸️ PAUSE"] --> D["Video Freezes"] E["⏹️ STOP"] --> F["Video Ends"] G["🔊 VOLUME"] --> H["Loud or Quiet"]

Full Video Player with Controls

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

function VideoPlayer() {
  const videoRef = useRef(null);
  const [paused, setPaused] = useState(false);

  return (
    <View>
      <Video
        ref={videoRef}
        source={{uri: 'https://example.com/video.mp4'}}
        style={{width: 320, height: 180}}
        paused={paused}
        resizeMode="contain"
      />

      <TouchableOpacity onPress={() => setPaused(!paused)}>
        <Text>{paused ? '▶️ Play' : '⏸️ Pause'}</Text>
      </TouchableOpacity>
    </View>
  );
}

Key Video Properties

Property What It Does Example
paused Stop/Start video true = stopped
volume How loud (0-1) 0.5 = half volume
muted Silent mode true = no sound
repeat Loop forever true = plays again
resizeMode How video fits "contain" or "cover"

🎵 Part 2: Audio Player

What is an Audio Player?

An audio player is like an invisible radio. You can’t see anything, but you can hear music, podcasts, or sounds!

The Simple Truth

For audio, we use react-native-track-player. It’s like hiring a professional DJ for your app!

Installation

npm install react-native-track-player

Setting Up the DJ (Initialization)

import TrackPlayer from 'react-native-track-player';

async function setupPlayer() {
  await TrackPlayer.setupPlayer();

  // Add a song to play
  await TrackPlayer.add({
    id: 'song1',
    url: 'https://example.com/song.mp3',
    title: 'My Favorite Song',
    artist: 'Cool Artist'
  });
}

Basic Audio Controls

// Play the music! 🎵
await TrackPlayer.play();

// Pause the music ⏸️
await TrackPlayer.pause();

// Skip to next song ⏭️
await TrackPlayer.skipToNext();

// Go back to previous song ⏮️
await TrackPlayer.skipToPrevious();

🎼 Audio Player Flow

graph TD A["📱 Your App"] --> B["Setup Player"] B --> C["Add Songs"] C --> D["Press Play"] D --> E["🎵 Music Plays!"] E --> F{User Action} F --> |Pause| G["⏸️ Music Stops"] F --> |Next| H["⏭️ New Song"] F --> |Volume| I["🔊 Louder/Quieter"]

Complete Audio Player Example

import React, { useEffect, useState } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import TrackPlayer, {
  usePlaybackState,
  State
} from 'react-native-track-player';

function AudioPlayer() {
  const playbackState = usePlaybackState();
  const isPlaying = playbackState === State.Playing;

  useEffect(() => {
    setupPlayer();
  }, []);

  async function setupPlayer() {
    await TrackPlayer.setupPlayer();
    await TrackPlayer.add({
      id: '1',
      url: 'https://example.com/song.mp3',
      title: 'Happy Song',
      artist: 'Fun Band'
    });
  }

  return (
    <View>
      <Text>🎵 Now Playing: Happy Song</Text>

      <TouchableOpacity
        onPress={() => isPlaying ?
          TrackPlayer.pause() :
          TrackPlayer.play()
        }
      >
        <Text>{isPlaying ? '⏸️ Pause' : '▶️ Play'}</Text>
      </TouchableOpacity>
    </View>
  );
}

🆚 Video vs Audio: Quick Comparison

Feature Video 📺 Audio 🎵
Shows pictures ✅ Yes ❌ No
Makes sound ✅ Yes ✅ Yes
Needs screen space ✅ Big ❌ Small controls
Background play ❌ Usually no ✅ Yes!
Library react-native-video react-native-track-player

🎯 Real-Life Examples

When to Use Video Player:

  • 🎬 Movie streaming app (like Netflix)
  • 📹 Watching tutorials
  • 📱 Video calls
  • 🎮 Game trailers

When to Use Audio Player:

  • 🎵 Music apps (like Spotify)
  • 🎙️ Podcast apps
  • 📚 Audiobooks
  • 🔔 Sound notifications

🧩 Handling Events (Listening to Your Players)

Video Events

<Video
  source={{uri: 'video.mp4'}}
  onLoad={(data) => {
    console.log('Video loaded!');
    console.log('Duration:', data.duration);
  }}
  onProgress={(data) => {
    console.log('Current time:', data.currentTime);
  }}
  onEnd={() => {
    console.log('Video finished!');
  }}
  onError={(error) => {
    console.log('Oops! Something broke:', error);
  }}
/>

Audio Events

import TrackPlayer, {
  Event
} from 'react-native-track-player';

// Listen when track changes
TrackPlayer.addEventListener(
  Event.PlaybackTrackChanged,
  async (data) => {
    console.log('New song playing!');
  }
);

// Listen when playback ends
TrackPlayer.addEventListener(
  Event.PlaybackQueueEnded,
  () => {
    console.log('All songs finished!');
  }
);

💡 Pro Tips (The Conductor’s Secrets!)

1. Always Handle Loading States

const [loading, setLoading] = useState(true);

<Video
  onLoad={() => setLoading(false)}
/>
{loading && <Text>Loading video...</Text>}

2. Clean Up When Done

useEffect(() => {
  return () => {
    TrackPlayer.reset(); // Stop audio when leaving
  };
}, []);

3. Handle Errors Gracefully

onError={(e) => {
  Alert.alert(
    'Oops!',
    'Could not play media. Check internet!'
  );
}}

🎬 Summary: You’re Now a Media Master!

graph TD A["🎓 You Learned"] --> B["📺 Video Player"] A --> C["🎵 Audio Player"] B --> D["react-native-video"] C --> E["react-native-track-player"] D --> F["Play/Pause/Controls"] E --> F F --> G["🌟 Build Amazing Apps!"]

Remember:

  • Video = Moving pictures with sound (needs screen space)
  • Audio = Sound only (can play in background)
  • Both = Your conductor’s baton to control media!

🚀 What’s Next?

Now you can:

  • ✅ Build a mini YouTube clone
  • ✅ Create a music player like Spotify
  • ✅ Add sound effects to games
  • ✅ Make video tutorials in your app

You did it! 🎉 You’re ready to make your apps sing and dance!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.