Media player xamarin android

Воспроизведение аудио-файлов в Xamarin.Forms

02.03.2016 в 23:20

Недавно мне было необходимо проиграть mp3-файл в одном из моих Xamarin.Forms приложений, когда я начал искать решение в интернете, то узнал о том, что в настоящий момент Xamarin.Forms приложения не поддерживают проигрывание аудио-файлов из коробки. Но, как знает всякий разработчик на Xamarin.Forms, мы можем использовать любую нативную функциональность по средствам dependency-сервисов, поэтому я решил попробовать и вот что получилось.

Нам потребуется создать интерфейс, который будет отдельно реализован на каждой конкретной платформе, я назвал его IAudio.cs :

Теперь мы должны написать класс содержащий реализацию интерфейса с использованием платформа специфичного кода. Я назвал этот класс AudioService на каждой платформе.

Класс для Android проекта выглядит так:

Убедитесь что файлы, которые вы хотите воспроизвести скопированы в директорию Assets , тогда код будет работать правильно.

И класс для iOS проекта:

В случае iOS проекта, вам нужно будет скопировать аудио-файлы в директорию Resources .

И, наконец, для воспроизведения аудио-файлов в нашем PCL/Shared проекте, воспользуемся следующим кодом:

Вы можете вызвать этот код при нажатии кнопки или любом другом событии в вашем PCL/Shared проекте. В приведенном выше примере я проигрывал МР3-файл, но вы можете использовать тот же самый код, чтобы воспроизвести любой другой аудио файл поддерживающийся платформой, например .aif (только в iOS), МР4, WAV и т.д.

Исходный код примера вы можете найти здесь.

Источник

Play Audio and Video with the MediaManager Plugin for Xamarin

March 21st, 2017

This is a special guest post on MediaManager for Xamarin, written by Xamarin MVP, Martijn van Dijk.

Martijn works at Xablu as a Xamarin consultant. You can find him on Twitter at @mhvdijk and on Github at @Martijn00.

Media apps, more than others, benefit from working together with the native platform. Some things, like handling interruptions with audio focus, network connectivity, and communication between notifications and other playback controls, make this a complicated matter.

To enable Xamarin developers to access these native platform functions, we decided to build a cross-platform Xamarin plugin that abstracts away the difficulties. We created a portable class library using the Bait & Switch pattern that contains all the interfaces for the native code, with the base classes shared across the apps to make it as easy as possible for you to interact with audio and video in your mobile apps.

The MediaManager Plugin for Xamarin is designed to be simple and easy-to-use, and has the following features:

  • Native playback of media files from remote and local sources
  • Native media notifications and remote controls
  • Playback status (Playing, Buffering, Loading, Paused, Progress)

Best of all, the MediaManager plugin works with all platforms, including iOS, Android, UWP, macOS, tvOS, and even Xamarin.Forms. In this blog post, we’ll explore the various components of the MediaManager Plugin for Xamarin and how you can easily integrate it into your mobile applications.

Audio

Both your eyes and ears are engaged when playing video. When playing audio, you’re listening, but you can also work with a different app at the same time. There’s a different design for each use case.

An audio player does not always need to have its user interface visible. Once it begins to play audio, the player can run as a background task. The user can switch to another app and work while continuing to listen.

To play audio takes only one line of code, and handles all of this for you:

Android ExoPlayer

ExoPlayer is an open source library that exposes the lower-level Android audio APIs. ExoPlayer supports high-performance features like DASH and HLS streaming that are not available in MediaPlayer. You can customize the ExoPlayer code, making it easy to add new components. ExoPlayer can only be used with Android version 4.1 and higher.

To make use of ExoPlayer, add the following code to your `MainActivity`:

Video

A video app needs a window for viewing content. For this reason, a video app is usually implemented on a single screen.

Notifications

A well-designed media app should “play well together” with other apps that play audio. It should be prepared to share the phone and cooperate with other apps on your device that use audio. It should also respond to hardware controls on the device, including:

  • Change the volume when the user adjusts a hardware volume control
  • Stop playing if the headphones are disconnected while in use
  • Stop playing, or lower the volume, when another app takes over the audio output stream

Media buttons are hardware buttons found on Android devices and other peripheral devices; for example, the pause/play button on a Bluetooth headset.

Queueing Audio and Video

If you want to play a sequence of media items, it’s helpful to have a queue. To add a list of media files to the queue, simply CrossMediaManager.Current.Play() an Enumerable of MediaFiles . With the queue, you are able to shuffle and repeat playback, loop through certain media files, and so on.

The queue can be accessed by:

Media Information

Media files contain a lot of information about the file. Details like title, album, artist, and more can be extracted from the metadata. It’s very easy to do this using the MediaManager:

Xamarin.Forms

The MediaManager can be used in a native app but also in a Xamarin.Forms app through a custom renderer for the Native Video view:

Make sure to call VideoViewRenderer.Init() from your platform code before starting playback, otherwise the view will not be prepared to display your video.

MediaManager In Action: The Scott Hanselman App!

Even the Hanselman App runs on the MediaManager, thanks to Erlend Angelsen! Using the implementation of MediaManager, the app now has improved audio playback, but what’s even more exciting is that all Hanselman videos from Channel 9 are available in the app! It also uses notifications to control the current media playing. In the future, this will be extended to make use of the queue and other advanced functionality. For more information about this app check out James Montemagno‘s Github repository.

Wrapping Up

There are many other samples for the Xamarin MediaManager available, including:

To get started, all you need to do is download the plugin from NuGet and install it into each project that utilizes MediaManager.

If you want to learn more about media playback, make sure to follow me on Twitter at @mhvdijk to receive updates. Future plans include support for Android Auto, Chromecast, CarPlay, and seamless switching between output sources such as Bluetooth, TV, or DLNA. If you have ideas, find bugs, or want to help with development, make sure to check out the source code on GitHub.

Источник

Android Audio

The Android OS provides extensive support for multimedia, encompassing both audio and video. This guide focuses on audio in Android and covers playing and recording audio using the built-in audio player and recorder classes, as well as the low-level audio API. It also covers working with Audio events broadcast by other applications, so that developers can build well-behaved applications.

Overview

Modern mobile devices have adopted functionality that formerly would have required dedicated pieces of equipment – cameras, music players and video recorders. Because of this, multimedia frameworks have become a first-class feature in mobile APIs.

Android provides extensive support for multimedia. This article examines working with audio in Android, and covers the following topics

Playing Audio with MediaPlayer – Using the built-in MediaPlayer class to play audio, including local audio files and streamed audio files with the AudioTrack class.

Recording Audio – Using the built-in MediaRecorder class to record audio.

Working with Audio Notifications – Using audio notifications to create well-behaved applications that respond correctly to events (such as incoming phone calls) by suspending or canceling their audio outputs.

Working with Low-Level Audio – Playing audio using the AudioTrack class by writing directly to memory buffers. Recording audio using the AudioRecord class and reading directly from memory buffers.

Requirements

This guide requires Android 2.0 (API level 5) or higher. Please note that debugging audio on Android must be done on a device.

It is necessary to request the RECORD_AUDIO permissions in AndroidManifest.XML:

Playing Audio with the MediaPlayer Class

The simplest way to play audio in Android is with the built-in MediaPlayer class. MediaPlayer can play either local or remote files by passing in the file path. However, MediaPlayer is very state-sensitive and calling one of its methods in the wrong state will cause an exception to be thrown. It’s important to interact with MediaPlayer in the order described below to avoid errors.

Initializing and Playing

Playing audio with MediaPlayer requires the following sequence:

Instantiate a new MediaPlayer object.

Configure the file to play via the SetDataSource method.

Call the Prepare method to initialize the player.

Call the Start method to start the audio playing.

The code sample below illustrates this usage:

Suspending and Resuming Playback

The playback can be suspended by calling the Pause method:

To resume paused playback, call the Start method. This will resume from the paused location in the playback:

Calling the Stop method on the player ends an ongoing playback:

When the player is no longer needed, the resources must be released by calling the Release method:

Using the MediaRecorder Class to Record Audio

The corollary to MediaPlayer for recording audio in Android is the MediaRecorder class. Like the MediaPlayer , it is state-sensitive and transitions through several states to get to the point where it can start recording. In order to record audio, the RECORD_AUDIO permission must be set. For instructions on how to set application permissions see Working with AndroidManifest.xml.

Initializing and Recording

Recording audio with the MediaRecorder requires the following steps:

Instantiate a new MediaRecorder object.

Specify which hardware device to use to capture the audio input via the SetAudioSource method.

Set the output file audio format using the SetOutputFormat method. For a list of supported audio types see Android Supported Media Formats.

Call the SetAudioEncoder method to set the audio encoding type.

Call the SetOutputFile method to specify the name of the output file that the audio data is written to.

Call the Prepare method to initialize the recorder.

Call the Start method to start recording.

The following code sample illustrates this sequence:

Stopping recording

To stop the recording, call the Stop method on the MediaRecorder :

Cleaning up

Once the MediaRecorder has been stopped, call the Reset method to put it back into its idle state:

When the MediaRecorder is no longer needed, its resources must be released by calling the Release method:

Managing Audio Notifications

The AudioManager Class

The AudioManager class provides access to audio notifications that let applications know when audio events occur. This service also provides access to other audio features, such as volume and ringer mode control. The AudioManager allows an application to handle audio notifications to control audio playback.

Managing Audio Focus

The audio resources of the device (the built-in player and recorder) are shared by all running applications.

Conceptually, this is similar to applications on a desktop computer where only one application has the keyboard focus: after selecting one of the running applications by mouse-clicking it, the keyboard input goes only to that application.

Audio focus is a similar idea and prevents more than one application from playing or recording audio at the same time. It is more complicated than keyboard focus because it is voluntary – the application can ignore that fact that it does not currently have audio focus and play regardless – and because there are different types of audio focus that can be requested. For example, if the requestor is only expected to play audio for a very short time, it may request transient focus.

Audio focus may be granted immediately, or initially denied and granted later. For example, if an application requests audio focus during a phone call, it will be denied, but focus may well be granted once the phone call is finished. In this case, a listener is registered in order to respond accordingly if audio focus is taken away. Requesting audio focus is used to determine whether or not it is OK to play or record audio.

For more information about audio focus, see Managing Audio Focus.

Registering the Callback for Audio Focus

Registering the FocusChangeListener callback from the IOnAudioChangeListener is an important part of obtaining and releasing audio focus. This is because the granting of audio focus may be deferred until a later time. For example, an application may request to play music while there is a phone call in progress. Audio focus will not be granted until the phone call is finished.

For this reason, the callback object is passed as a parameter into the GetAudioFocus method of the AudioManager , and it is this call that registers the callback. If audio focus is initially denied but later granted, the application is informed by invoking OnAudioFocusChange on the callback. The same method is used to tell the application that audio focus is being taken away.

When the application has finished using the audio resources, it calls the AbandonFocus method of the AudioManager , and again passes in the callback. This deregisters the callback and releases the audio resources, so that other applications may obtain audio focus.

Requesting Audio Focus

The steps required to request the audio resources of the device are as follow:

Obtain a handle to the AudioManager system service.

Create an instance of the callback class.

Request the audio resources of the device by calling the RequestAudioFocus method on the AudioManager . The parameters are the callback object, the stream type (music, voice call, ring etc.) and the type of the access right being requested (the audio resources can be requested momentarily or for an indefinite period, for example).

If the request is granted, the playMusic method is invoked immediately, and the audio starts to play back.

If the request is denied, no further action is taken. In this case, the audio will only play if the request is granted at a later time.

The code sample below shows these steps:

Releasing Audio Focus

When the playback of the track is complete, the AbandonFocus method on AudioManager is invoked. This allows another application to gain the audio resources of the device. Other applications will receive a notification of this audio focus change if they have registered their own listeners.

Low Level Audio API

The low-level audio APIs provide a greater control over audio playing and recording because they interact directly with memory buffers instead of using file URIs. There are some scenarios where this approach is preferable. Such scenarios include:

When playing from encrypted audio files.

When playing a succession of short clips.

AudioTrack Class

The AudioTrack class uses the low-level audio APIs for recording, and is the low-level equivalent of the MediaPlayer class.

Initializing and Playing

To play audio, a new instance of AudioTrack must be instantiated. The argument list passed into the constructor specifies how to play the audio sample contained in the buffer. The arguments are:

Stream type – Voice, ringtone, music, system or alarm.

Frequency – The sampling rate expressed in Hz.

Channel Configuration – Mono or stereo.

Audio format – 8 bit or 16 bit encoding.

Buffer size – in bytes.

Buffer mode – streaming or static.

After construction, the Play method of AudioTrack is invoked, to set it up to start playing. Writing the audio buffer to the AudioTrack starts the playback:

Pausing and Stopping the Playback

Call the Pause method to pause the playback:

Calling the Stop method will terminate the playback permanently:

Cleanup

When the AudioTrack is no longer needed, its resources must be released by calling Release:

The AudioRecord Class

The AudioRecord class is the equivalent of AudioTrack on the recording side. Like AudioTrack , it uses memory buffers directly, in place of files and URIs. It requires that the RECORD_AUDIO permission be set in the manifest.

Initializing and Recording

The first step is to construct a new AudioRecord object. The argument list passed into the constructor provides all the information required for recording. Unlike in AudioTrack , where the arguments are largely enumerations, the equivalent arguments in AudioRecord are integers. These include:

Hardware audio input source such as microphone.

Stream type – Voice, ringtone, music, system or alarm.

Frequency – The sampling rate expressed in Hz.

Channel Configuration – Mono or stereo.

Audio format – 8 bit or 16 bit encoding.

Buffer size-in bytes

Once the AudioRecord is constructed, its StartRecording method is invoked. It is now ready to begin recording. The AudioRecord continuously reads the audio buffer for input, and writes this input out to an audio file.

Stopping the Recording

Calling the Stop method terminates the recording:

Cleanup

When the AudioRecord object is no longer needed, calling its Release method releases all resources associated with it:

Summary

The Android OS provides a powerful framework for playing, recording and managing audio. This article covered how to play and record audio using the high-level MediaPlayer and MediaRecorder classes. Next, it explored how to use audio notifications to share the audio resources of the device between different applications. Finally, it dealt with how to playback and record audio using the low-level APIs, which interface directly with memory buffers.

Источник

Читайте также:  Viber для андроид стикеры
Оцените статью